【问题标题】:Python access dictionary inside list of a dictionary字典列表中的Python访问字典
【发布时间】:2017-08-09 13:35:04
【问题描述】:

您好,我有下面的字典,它有一个带有列表的值,列表里面是一个字典。有没有办法使用键而不是列表索引来调用列表中的字典值?列表中的字典可能会有所不同,因此索引值可能并不总是提供正确的键值对。但如果我能够使用密钥,我总能得到正确的值。

mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}
print(mylist['mydict'][0]['A'])

电流输出:

Letter A

所需查询:

print(mylist['mydict']['A'])
Letter A

【问题讨论】:

  • 为什么不直接使用一个字典?
  • 如果不更改对象的结构,就无法更改所需查询的结果。使用当前结构,查询总是会引发错误。
  • 看起来你应该做mydicts = {k: dict(v) for k, v in mylist.items()}然后你得到可以用作mydicts['mydict']['A']的结构

标签: python list dictionary


【解决方案1】:

看看下面的代码:

mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}

for dictionary in mylist['mydict']:
   try:
      print(dictionary['A'])
   except KeyError:
      pass
'Letter A'

您遍历列表中的字典,然后尝试调用您的 A 键。你抓住了KeyError,因为字典中的键可能不存在。

【讨论】:

    【解决方案2】:

    尝试下面的代码来生成新的字典。

    mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}
    newDict={}
    for item in mylist['mydict']:
        newDict.update(item)
    mylist['mydict']=newDict
    print(mylist['mydict']['A'])
    

    【讨论】:

      【解决方案3】:

      目前,您在字典中的列表中有 3 个字典。请尝试以下方法:

      my_nested_dictionary = {'mydict': {'A': 'Letter A', 'B': 'Letter C', 'C': 'Letter C'}}
      print(my_nested_dictionary['mydict']['A'])
      

      【讨论】:

      • 我遍历数据来创建它并使用 .append({key: value}) 来创建带有字典的列表。让我看看我是否可以像这样格式化它。这有帮助,谢谢。
      • 在这种情况下,您可以初始化 mylist = {'mydict': {}} 并在 keyvalue 上使用 for 循环并拥有 mylist['mydict'][key] = value
      【解决方案4】:

      使用生成器怎么样?

      item = next(item['A'] for item in mylist['mydict'] if 'A' in item)
      

      【讨论】:

        【解决方案5】:

        只有当您的原始数据格式为:

        mylist = {'mydict': {'A': 'Letter A','B': 'Letter C','C': 'Letter C'}}
        

        所以没有嵌入列表 - 这似乎并没有添加有意义的结构?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-15
          • 1970-01-01
          • 1970-01-01
          • 2019-02-13
          • 2018-02-06
          • 1970-01-01
          相关资源
          最近更新 更多