How to Print All Values of a Given Key in a List of Dictionaries in Python?

Estimated read time 2 min read

To print all values of a given key in a list of dictionaries in Python, you can use a loop to iterate over each dictionary in the list and access the value associated with the given key. Here is an example:

people = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 25},
    {'name': 'David', 'age': 35},
    {'name': 'Eve', 'age': 30}
]

ages = []
for person in people:
    age = person.get('age')
    if age is not None:
        ages.append(age)

print(ages)

In this example, the people list contains five dictionaries, each representing a person with a name and an age. The goal is to print all the ages in the list.

To do this, we first create an empty list called ages. Then we use a for loop to iterate over each person in the people list. For each person, we use the dictionary method get() to access the value associated with the key 'age'. If the key is not present in the dictionary, get() returns None. Therefore, we check if the result of get() is not None using an if statement. If the result is not None, we append the age to the ages list.

Finally, we print the contents of the ages list using the print() function. This will output all the ages in the list of dictionaries. In this example, the output will be [25, 30, 25, 35, 30].

Note that in this example, we assume that all dictionaries in the list have an 'age' key. If some dictionaries do not have this key, we use the if statement to avoid adding None values to the ages list. If you are certain that all dictionaries have the 'age' key, you can simplify the code by omitting the if statement and directly appending the age to the ages list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply