【发布时间】:2018-03-30 18:01:23
【问题描述】:
我正在对嵌套字典使用列表推导来查找键“流”的值,这些键出现在某些字典中但不是全部出现(在示例中为“DE”和“CH”,但不是“FR”)。如果它不存在,它应该跳过这个字典并移动到下一个字典。
我的数据:
dict_country_data =
{"DE":
{
"location":
"europe",
"country_code":
"DE",
"color":
{"body": 37647, "wheels": 37863},
"size":
{"extras": 40138},
"flow":
{"abc": 3845, "cdf": 3844}
},
"FR":
{"location": "europe",
"country_code": "FR",
"color":
{"body": 219107, "wheels": 39197},
"size":
{"extras": 3520}
},
"CH":
{"location": "europe",
"country_code": "CH",
"color": {"wheels": 39918},
"size":
{"extras": 206275},
"flow":
{"klm": 799, "sas": 810}
}
}
我的尝试:
[dict_country_data[k]["flow"].values() if dict_country_data[k]["flow"].keys() else None for k,v in dict_country_data.items()]
然而,尽管有 if 语句,Python 还是会引发 NamError(NameError: name 'flow' is not defined)。
我渴望的输出:
[3845, 3844, 799, 810]
感谢您的耐心和帮助。
【问题讨论】:
标签: python list dictionary nested list-comprehension