[英]Get specific value in python nested dictionary
So when I print dictionary it gives: 所以当我打印字典时,它给出:
u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}]
I need value of Key 'Name' ie "Hello world" 我需要键“名称”的值,即“ Hello world”
I tried this: 我尝试了这个:
for t in Tags:
print(t["Name"])
but get error: 但得到错误:
KeyError: 'Name'
In the dictionary, the entry Tags
points to a list of objects with key and value as nested entries. 在字典中,“
Tags
”条目指向具有键和值作为嵌套条目的对象列表。 Therefore, the access is not direct and requires a search of the key. 因此,访问不是直接的,需要搜索密钥。 It can be done using a simple list comprehension:
可以使用简单的列表理解来完成:
d = {u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'},
{u'Value': 'hello world', u'Key': 'Name'},
{u'Value': '123 Street', u'Key': 'Address'}]}
name = next((v for v in d['Tags'] if v['Key'] == 'Name'), {}).get('Value')
'Name'
here is not a key, it is a value. 'Name'
不是键,而是值。 Your dictionaries all have keys of u'Key'
and u'Value'
which might be slightly confusing. 您的词典都具有
u'Key'
和u'Value'
键,这可能会造成一些混淆。
This should work for your example though: 不过,这应该适用于您的示例:
for t in Tags:
if t['Key'] == 'Name':
print t['Value']
If you want to find a "key name": 如果要查找“键名”:
findYourWord ='hello world'
for dictB in dictA[u'Tags']:
for key in dictB:
if dictB[key]== findYourWord:
print(key)
Hope this help you. 希望这对您有所帮助。 Have a nice day.
祝你今天愉快。
In your inner dictionaries, the only keys are 'Key' and 'Value'. 在内部词典中,唯一的键是“键”和“值”。 Try to make a function to find the value of the key you want, try:
尝试使函数查找所需键的值,请尝试:
def find_value(list_to_search, tag_to_find):
for inner_dict in list_to_search:
if inner_dict['Key'] == tag_to_find:
return inner_dict['Value']
Now: 现在:
In [1]: my_dict = {u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}]}
In [2]: find_value(my_dict['Tags'], 'Name')
Out[2]: 'hello world'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.