我有一份dict的列表......
categories = [{'summarycategory': {'amount':1233}},
{'hhCategory': {}},
{'information': {'mRoles': ['4456'],
'cRoles': None,
'emcRoles': ['spm/4456']}}]
我想获得价值信息.mcRoles。要做到这一点,我做:
for x in categories:
for key in x:
if key == "information":
print(x[key]["emcRoles"])
必须有更多的pythonic方式?
此外,需要它是null安全的。因此,如果"information"
不存在,我就不希望空指针查找emcRoles。
答案 0 :(得分:3)
键上没有循环,你要杀死使用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"])
要创建这些信息的列表,请使用带有条件的listcomp(同样,listcomp使得难以避免双dict键访问):
[x["information"]["emcRoles"] for x in categories if "information" in x]
答案 1 :(得分:2)
单行:
next(x for x in categories if 'information' in x)['information']['emcRoles']
答案 2 :(得分:1)
如果information
或emcRoles
可能丢失,您可以“请求原谅”,将其全部包装在try..except
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"))
答案 3 :(得分:1)
根据您对类别列表的其他操作,将您的词典列表转换为新词典可能有意义:
newdictionary=dict([(key,d[key]) for d in categories for key in d])
print(newdictionary['information']['emcRoles'])
有关详情,请参阅how to convert list of dict to dict。