Extract Specific Key Values from a List of Dictionaries in Python

Modified: | Tags: Python, List, Dictionary

This article explains how to get a list of specific key values from a list of dictionaries with common keys in Python.

Lists of dictionaries are frequently encountered when reading JSON; see the following article on reading and writing JSON in Python.

Note that a list of dictionaries can be converted to pandas.DataFrame.

Extract specific key values using list comprehension and the get() method

Use list comprehension in combination with the get() method of dictionaries.

l = [
    {'Name': 'Alice', 'Age': 40, 'Point': 80},
    {'Name': 'Bob', 'Age': 20},
    {'Name': 'Charlie', 'Age': 30, 'Point': 70},
]

l_name = [d.get('Name') for d in l]
print(l_name)
# ['Alice', 'Bob', 'Charlie']

l_age = [d.get('Age') for d in l]
print(l_age)
# [40, 20, 30]

l_point = [d.get('Point') for d in l]
print(l_point)
# [80, None, 70]

For more information about list comprehension and the get() method, refer to these articles:

Handling elements that lack common keys

As demonstrated above, if the key does not exist, the get() method returns None by default.

l = [
    {'Name': 'Alice', 'Age': 40, 'Point': 80},
    {'Name': 'Bob', 'Age': 20},
    {'Name': 'Charlie', 'Age': 30, 'Point': 70},
]

l_point = [d.get('Point') for d in l]
print(l_point)
# [80, None, 70]

You can provide a default value as the second argument.

l_point_default = [d.get('Point', 0) for d in l]
print(l_point_default)
# [80, 0, 70]

To exclude elements without the specified key, you can add an if condition to the list comprehension.

l_point_ignore = [d.get('Point') for d in l if d.get('Point')]
print(l_point_ignore)
# [80, 70]

To avoid repeatedly calling the get() method, you can use the assignment expression, also known as the Walrus operator :=. This operator, introduced in Python 3.8, allows you to assign values to variables as part of an expression.

l_point_ignore_walrus = [v for d in l if (v := d.get('Point'))]
print(l_point_ignore_walrus)
# [80, 70]

Related Categories

Related Articles