简体   繁体   中英

Find value of key in nested Dict in list comprehension if key available available

I am using list comprehension for a nested dict looking for the values for the keys "flow" which occures in some dict but not in all (in the example "DE" and "CH", but not "FR"). If it does not exist, it should skip this dict and move to the next dict.

My data:

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}
         }
} 

My attempt:

[dict_country_data[k]["flow"].values() if dict_country_data[k]["flow"].keys() else None for k,v in dict_country_data.items()] 

However, despite the if-Statement, Python raises a NamError (NameError: name 'flow' is not defined).

My aspired output:

[3845, 3844, 799, 810]

Thank you for you patience and helpfulness.

像这样“展平”的常用方法是嵌套理解:

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

You don't get a NameError, but a KeyError, because you try to access the key "flow" for each entry. Instead of putting everything in one list comprehension, use a for -loop, which is more readable:

flows = []
for data in dict_country_data.values():
    if "flow" in data:
        flows.extend(data["flow"].values())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM