字典列表中的 Python 访问字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45592268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:08:54  来源:igfitidea点击:

Python access dictionary inside list of a dictionary

pythonlistdictionary

提问by MBasith

Hi I have the below dictionary which has a value with a list, and inside the list is a dictionary. Is there a way to call the dictionary value inside the list using the key instead of the list index? The dictionary inside the list may vary so the index value may not always provide the right key value pair. But if I am able to use the key I can always get the correct value.

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

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

Current Output:

电流输出:

Letter A

Desired Query:

所需查询:

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

回答by M3RS

At the moment you have 3 dictionaries inside a list inside a dictionary. Try the below instead:

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

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

回答by Laszlowaty

Take a look at the code below:

看看下面的代码:

>>> mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}
>>> for dictionary in mylist['mydict']:
...  try:
...   dictionary['A']
...  except KeyError:
...   pass
... 
'Letter A'

You iterate over a dictionaries inside your list, and then try to call your Akey. You catch KeyErrorbecause in the dictionary key may be absent.

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

回答by aristotll

Try the following code to generate the new dict.

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

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'])

回答by Dmytro Chekunov

How about using a generator?

使用发电机怎么样?

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

回答by Thijs Cobben

This is only possible if your original data is formatted as:

仅当您的原始数据格式为:

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

so without the embedded list - which doesn't seem to add meaningful structure anyway?

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