Python 从Dict';列表中的特定Dict中提取特定值;s

Python 从Dict';列表中的特定Dict中提取特定值;s,python,python-3.x,Python,Python 3.x,我有一张迪克特的名单 categories = [{'summarycategory': {'amount':1233}}, {'hhCategory': {}}, {'information': {'mRoles': ['4456'], 'cRoles': None, 'emcRoles': ['spm/4456']}}]

我有一张迪克特的名单

categories = [{'summarycategory': {'amount':1233}},
             {'hhCategory': {}},
             {'information': {'mRoles': ['4456'],
                              'cRoles': None,
                              'emcRoles': ['spm/4456']}}]
我想得到有价值的信息。为此,我要:

for x in categories:
    for key in x:
        if key == "information":
            print(x[key]["emcRoles"])
一定有更像蟒蛇的方式? 此外,它需要是空安全的。因此,如果,
“信息”
不在那里,我不想要一个查找emcRoles的空指针。

不要在键上循环,你正在停止使用dict键查找(普通循环是
O(n)
,dict查找是
O(1)

取而代之的是,只需检查密钥是否属于,如果属于,就去拿它

for x in categories:
    if "information" in x:
        print(x["information"]["emcRoles"])
或者使用
dict.get
保存dict密钥访问:

for x in categories:
    d = x.get("information")
    if d is not None:   # "if d:" would work as well here
        print(d["emcRoles"])
[x["information"]["emcRoles"] for x in categories if "information" in x]
要创建这些信息的列表,请使用带有条件的listcomp(同样,listcomp使避免双dict键访问变得困难):


如果
信息
emcRoles
可能丢失,您可以通过将其全部包装在
try

try:
    for x in categories:
        if "information" in x:
            print(x["information"]["emcRoles"])
except:
    # handle gracefully ...
或者您可以使用
get()
并提供您认为合适的回退值:

for x in categories:
    print(x.get("information", {}).get("emcRoles", "fallback_value"))
一行:

next(x for x in categories if 'information' in x)['information']['emcRoles']

根据您对类别列表所做的其他操作,将词典列表转换为新词典可能是有意义的:

newdictionary=dict([(key,d[key]) for d in categories for key in d])
print(newdictionary['information']['emcRoles'])

更多信息,请参见。

是否
emcRoles
始终位于
信息
下?是否总是只有一个带有
信息
键的词典?或者是否需要满足多个词典/匹配项的要求?对于列表选项,我认为这取决于词典中包含“信息”的百分比。如果它是一个常用的/预期的键,那么除了
x.get(…,{})。get(…,None)
可能更合适。如果它不是预期的,那么您的方法看起来不错。是的,同时使用
get
可以保存dict访问。