简体   繁体   中英

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"

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. 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. Your dictionaries all have keys of u'Key' and u'Value' which might be slightly confusing.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM