【问题标题】:Pull a specific value from a specific Dict in a List of Dict's从字典列表中的特定字典中提取特定值
【发布时间】:2018-08-30 18:33:10
【问题描述】:

我有一个 dict 的列表...

categories = [{'summarycategory': {'amount':1233}},
             {'hhCategory': {}},
             {'information': {'mRoles': ['4456'],
                              'cRoles': None,
                              'emcRoles': ['spm/4456']}}]

我想获取价值信息.emcRoles。为此,我这样做:

for x in categories:
    for key in x:
        if key == "information":
            print(x[key]["emcRoles"])

一定有更pythonic的方式吗? 此外,它需要是空安全的。因此,如果 "information" 不存在,我不希望空指针查找 emcRoles。

【问题讨论】:

  • emcRoles 总是在information 下吗?
  • 总是只有 一个 字典带有information 键吗?还是您需要满足多个字典/匹配项?

标签: python python-3.x


【解决方案1】:

不要在键上循环,你正在扼杀 dict 键查找的使用(普通循环是 O(n),dict 查找是 O(1)

相反,只需检查 key 是否属于,如果是则去获取它。

for x in categories:
    if "information" in x:
        print(x["information"]["emcRoles"])

或使用dict.get 保存字典键访问:

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]

【讨论】:

  • 对于列表选项,我想说这取决于字典中包含“信息”的百分比。如果它是常用的 /expected 键,那么 try / exceptx.get(..., {}).get(..., None) 可能更合适。如果不是预期的,那么您的方法看起来不错。
  • 是的,同样使用get 可以节省字典访问权限。
【解决方案2】:

单行:

next(x for x in categories if 'information' in x)['information']['emcRoles']

【讨论】:

    【解决方案3】:

    如果informationemcRoles 可能丢失,您可以“请求宽恕”,将其全部包裹在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"))
    

    【讨论】:

      【解决方案4】:

      根据您对类别列表所做的其他操作,将您的词典列表转换为新词典可能是有意义的:

      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 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-10
        • 2020-04-18
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-23
        相关资源
        最近更新 更多