Skip to main content
 首页 » 编程设计

python之如果键可用,则在列表理解中查找嵌套字典中键的值

2025年01月19日11emanlee

我正在对嵌套字典使用列表推导式来查找出现在某些字典中但并非全部出现的键“流”的值(在示例中为“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:未定义名称“flow”)。

我期望的输出:

[3845, 3844, 799, 810] 

感谢您的耐心和帮助。

请您参考如下方法:

像这样“扁平化”的通常方法是使用嵌套理解:

[v for country, data in dict_country_data.items() for v in data['flow'].values()]