Home > Back-end >  How to retrieve data of a key in dictionary which is nested in list simultaneously
How to retrieve data of a key in dictionary which is nested in list simultaneously

Time:10-17

data = [
    {
        'name1': 'aaa',
    },
    {
        'name2': 'bbb',
    },
    {
        'name3': 'ccc',
    },
    {
        'name4': 'ddd',
    }
]

Now how can I retrieve data of key >>name1 (i.e aaa ) with index no. of the list simultaneously.

CodePudding user response:

Method

  • Use enumerate to provide index of each dictionary as you loop.
  • Use dictionary.items() to retrieve key, value pairs of each dictionary

Code

def get_value(data, key):
        ' Retrieves index of dictionary and value with key key'
        for i, d in enumerate(data):
            for k, v in d.items():
                if k == key:
                    return i, v    # return index and value of dictionary
            

Test

print(get_value(data, 'name1'))
# Output: (0, 'aaa')

CodePudding user response:

You access list with index as int, you access a dict with index as the key, no matter the type

data = [
    {'name1': 'aaa', },
    {'name2': 'bbb', },
    {'name3': 'ccc', },
    {'name4': 'ddd', }
]

x = data[0]['name1']
print(x)  # aaa

Example with key type int

data = [{'name1': 'aaa'}, {0: 'ddd'}]
x = data[1][0]
print(x)  # ddd
  • Related