Python list of dictionaries get value | Example code

  • by

To get the value of a list of dictionaries first we have to access the dictionary using indexing.

list_data[index][key]

Example list of dictionaries get value in Python

Simple example code.

data = [{101: 'Any', 102: 'Bob'},
         {103: 'John', 105: 'Tim'}]

# display data of key 101
print(data[0][101])

# display data of key 105
print(data[1][105])

Output:

Python list of dictionaries get value

Access the key:value pairs from the list of dictionaries

We can easily access any key:value pair of the dictionary, just pass the index value of the dictionary in square bracket [].

data = [{101: 'Any', 102: 'Bob'},
         {103: 'John', 105: 'Tim'}]

print(data[1])

Output:

{103: ‘John’, 105: ‘Tim’}

Get all values of specific key

data = [{'value': 'apple', 'blah': 2},
        {'value': 'banana', 'blah': 3},
        {'value': 'cars', 'blah': 4}]

res = [d['value'] for d in data]

print(res)

Output: [‘apple’, ‘banana’, ‘cars’]

Get all values of the list dictionary

my_dict = [{'value': 'apple', 'blah': 2},
           {'value': 'banana', 'blah': 3},
           {'value': 'cars', 'blah': 4}]

res = []

for key in my_dict:
    for value in key:
        res.append(key.values())

print(res)

Output:

[dict_values(['apple', 2]), dict_values(['apple', 2]), dict_values(['banana', 3]), dict_values(['banana', 3]), dict_values(['cars', 4]), dict_values(['cars', 4])]

Do comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.