[英]Iterate through nested Dictionary Object and get the value of specific object in Python
[英]Get specific value in python nested dictionary
所以当我打印字典时,它给出:
u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}]
我需要键“名称”的值,即“ Hello world”
我尝试了这个:
for t in Tags:
print(t["Name"])
但得到错误:
KeyError: 'Name'
在字典中,“ Tags
”条目指向具有键和值作为嵌套条目的对象列表。 因此,访问不是直接的,需要搜索密钥。 可以使用简单的列表理解来完成:
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'
不是键,而是值。 您的词典都具有u'Key'
和u'Value'
键,这可能会造成一些混淆。
不过,这应该适用于您的示例:
for t in Tags:
if t['Key'] == 'Name':
print t['Value']
如果要查找“键名”:
findYourWord ='hello world'
for dictB in dictA[u'Tags']:
for key in dictB:
if dictB[key]== findYourWord:
print(key)
希望这对您有所帮助。 祝你今天愉快。
在内部词典中,唯一的键是“键”和“值”。 尝试使函数查找所需键的值,请尝试:
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']
现在:
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.