Get the Value of a Key From a List of Dictionaries With Python

Dictionaries are used to store complex data structures and knowing how to retrieve data from dictionaries is a critical skill for Python developers. The focus of this tutorial is to show you how to extract the value of a specific key from a list of dictionaries.

This scenario is very common in real-world tasks, such as processing JSON data from a Web API or handling configuration settings in applications.

You will learn different ways to do it so you can select the one that works best for the Python program you are writing.

Retrieve the Value of a Key From a List of Dictionaries Using a Python For Loop

The most basic approach to extract a key from a list of dictionaries is to use a Python for loop.

This is usually the first approach a developer would come up with if they are beginners with Python. And that’s fine, considering that it’s important to master the basics of Python before coming up with more Pythonic approaches.

Here is a list of dictionaries we can work with. Every dictionary contains firstname and lastname to describe a person:

people = [{'firstname':'John', 'lastname':'Ross'}, {'firstname':'Mark', 'lastname':'Green'}]

Now create a for loop that goes through each dictionary and extracts the firstname:

firstnames = []

for person in people:
    firstnames.append(person['firstname'])
    
print(firstnames)

The output of the print statement shows that the logic of this code is correct:

['John', 'Mark']

Here is a breakdown of the code line by line:

  1. firstnames = []: This line initializes an empty list called firstnames. We will add the first names extracted from each dictionary in the people list to this list.
  2. for person in people: This line starts a for loop. Each iteration of the loop takes one dictionary from the people list and assigns it to the variable person.
  3. firstnames.append(person['firstname']): Inside the loop, for each person (which is a dictionary), the code extracts the value associated with the key 'firstname'. It then appends this value to the firstnames list using the append() method.

Let’s now explore a different approach.

Get the Value of a Specific Key From a List of Dictionaries Using a List Comprehension

The next natural step to a for loop is to look at how you can implement the same logic with a list comprehension.

List comprehensions provide a way to write code concisely and elegantly, and sometimes using those instead of a for loop can represent the best option.

Let’s implement the logic that gets the firstnames from the list of dictionaries using a list comprehension:

people = [{'firstname':'John', 'lastname':'Ross'}, {'firstname':'Mark', 'lastname':'Green'}]
firstnames = [person['firstname'] for person in people]
print(firstnames)

The output is the same as you have seen with a for loop:

['John', 'Mark']

The list comprehension iterates over each person in the people list, extracts person['firstname'], and collects these first names into a new list called firstnames.

With a single line of code, you have replaced the entire for loop and append operation from the original code. That’s great!

Extract the Value of a Key From a List of Dictionaries Using a Lambda Function

In this section, we will use the same list of dictionaries used in the previous two sections.

Let’s see how to use a lambda function to extract a specific attribute from a list of dictionaries.

Python provides the map() built-in function that used together with a lambda function allows you to extract the value of a specific attribute from a list of dictionaries.

Let’s say you want to extract the firstname value from every dictionary in the list. First, create a lambda function that takes one dictionary as the argument and returns the value of the firstname key.

lambda person : person['firstname']

Test this lambda in the Python shell with the first dictionary of our test list:

>>> (lambda person : person['firstname'])({'firstname':'John', 'lastname':'Ross'})
'John'

Then pass this lambda to the map() function. Here is the syntax of the map() built-in function:

map(function, iterable, *iterables)

Note: the map() function can accept multiple iterables and in this example, we will be passing one iterable to it, our list of dictionaries.

The arguments you will pass to the map() function are:

  • First argument: the lambda function you just created.
  • Second argument: the list of dictionaries from which we want to extract the firstname attribute.

Here is what the full expression looks like:

firstnames = list(map(lambda person : person['firstname'], people))

Let’s test this code:

>>> people = [{'firstname':'John', 'lastname':'Ross'}, {'firstname':'Mark', 'lastname':'Green'}]
>>> firstnames = list(map(lambda person : person['firstname'], people))
>>> firstnames
['John', 'Mark']

The result is correct. This is a very powerful approach.

Conclusion

In this tutorial, we have explored three methods in Python to get the value of a specific key from a list of dictionaries:

  • Traditional for loop combined with the append method to create a new list of first names. This approach is straightforward and quite intuitive, especially for those new to Python.
  • List comprehension. This is a more Pythonic way of achieving the same result in just one line of code. List comprehensions not only reduce the amount of code but also enhance readability.
  • The map() and lambda functions. This approach is less readable than the previous two especially if you are just getting started with Python. At the same time, it’s a good exercise to expand your Python knowledge.

Understanding these three techniques gives you all you need to choose the implementation you prefer.

Related article: Would you like to learn more about Python lambdas? Go through the introductory CodeFatherTech tutorial about Python lambdas.

Leave a Comment