【问题标题】:Find value of key in nested Dict in list comprehension if key available available如果键可用,则在列表理解中查找嵌套 Dict 中键的值
【发布时间】: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


    【解决方案1】:

    像这样“展平”的常用方法是使用嵌套推导:

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

    【讨论】:

      【解决方案2】:

      您不会得到 NameError,而是 KeyError,因为您尝试访问每个条目的键 "flow"。 不要将所有内容都放在一个列表理解中,而是使用for-loop,这样更具可读性:

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

      【讨论】:

        猜你喜欢
        • 2014-10-25
        • 2020-04-15
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 2022-06-15
        • 2022-01-06
        • 2019-11-12
        • 1970-01-01
        相关资源
        最近更新 更多