﻿ Python: Convert a list of dictionaries into a list of values corresponding to the specified key - w3resource

Python: Convert a list of dictionaries into a list of values corresponding to the specified key

Python dictionary: Exercise-73 with Solution

Write a Python program to convert a list of dictionaries into a list of values corresponding to the specified key.

• Use a list comprehension and dict.get() to get the value of key for each dictionary in lst.

Sample Solution:

Python Code:

``````# Define a function 'test' that takes a list of dictionaries 'lsts' and a 'key'.
def test(lsts, key):
# Use a list comprehension to extract the value associated with the specified 'key' from each dictionary.
return [x.get(key) for x in lsts]

# Create a list of dictionaries 'students', where each dictionary contains 'name' and 'age' keys.
students = [
{'name': 'Theodore', 'age': 18},
{'name': 'Mathew', 'age': 22},
{'name': 'Roxanne', 'age': 20},
{'name': 'David', 'age': 18}
]

# Print the original list of dictionaries.
print("Original list of dictionaries:")
print(students)

# Call the 'test' function to extract 'age' values from the 'students' list of dictionaries.
print("\nConvert a list of dictionaries into a list of values corresponding to the specified key:")
print(test(students, 'age'))
```
```

Sample Output:

```Original list of dictionaries:
[{'name': 'Theodore', 'age': 18}, {'name': 'Mathew', 'age': 22}, {'name': 'Roxanne', 'age': 20}, {'name': 'David', 'age': 18}]

Convert a list of dictionaries into a list of values corresponding to the specified key:
[18, 22, 20, 18]
```

Flowchart:

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿