Python: Convert a list of dictionaries into a list of values corresponding to the specified key
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:
Previous: Write a Python program to invert a dictionary with unique hashable values.
Next: Write a Python program to create a dictionary with the same keys as the given dictionary and values generated by running the given function for each value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics