Skip to content

Python list of dictionaries get value | Example code

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 a 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])]

To get the value of a specific key in a list of dictionaries in Python, you can use a loop to iterate through the list and access the key you’re interested in for each dictionary. Here’s an example of how to do it:

# Sample list of dictionaries
data = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]

# Key you want to access
key_to_access = 'age'

# Iterate through the list of dictionaries and get the value for the specified key
values = [item[key_to_access] for item in data]

# Print the values
for value in values:
    print(value)

In this example, we have a list of dictionaries containing information about people, and we want to access the ‘age’ key for each person. The list comprehension [item[key_to_access] for item in data] is used to extract the values associated with the ‘age’ key from each dictionary in the list.

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

Note: IDE: PyCharm 2021.3.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.

1 thought on “Python list of dictionaries get value | Example code”

  1. Hi, i was just wondering, how can i get all values of the list dictionary , depending on user input, ex: if user select first and second list, how can i fetch it from the dictionary?

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading