在python嵌套字典中获取特定值
因此,当我打印字典时,它给出:在python嵌套字典中获取特定值,python,dictionary,Python,Dictionary,因此,当我打印字典时,它给出: u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}] 我需要键“Name”的值I-e Hello world 我试过这个: for t in Tags: print(t["Name"]) 但是得到错误: KeyError: '
u'Tags': [{u'Value': 'stone', u'Key': 'primary-key'}, {u'Value': 'hello world', u'Key': 'Name'}, {u'Value': '123 Street', u'Key': 'Address'}]
我需要键“Name”的值I-e Hello world
我试过这个:
for t in Tags:
print(t["Name"])
但是得到错误:
KeyError: 'Name'
在字典中,条目标记指向一个对象列表,其中键和值为嵌套条目。因此,访问不是直接的,需要搜索密钥。可以使用简单的列表理解来完成:
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')
如果要查找密钥名称,请执行以下操作:
findYourWord ='hello world'
for dictB in dictA[u'Tags']:
for key in dictB:
if dictB[key]== findYourWord:
print(key)
希望这对你有帮助。祝你有一个愉快的一天。'Name'这里不是一个键,而是一个值。您的字典都有u'Key'和u'Value'键,这可能会有点混淆
不过,这应该适用于您的示例:
for t in Tags:
if t['Key'] == 'Name':
print t['Value']
在内部字典中,唯一的键是“Key”和“Value”。尝试创建函数以查找所需键的值,请尝试:
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']
现在:
名字就是价值!您必须使用keyu'Value':'hello world'->t['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'