Python Practice › List Programs › Program 35
Keys and values from a list of dicts
Write a Python program to get all keys and all values from a list of single-item dictionaries.
Input
[{"a": 12}, {"b": 34}, {"c": 23}, {"d": 11}, {"e": 15}]Output
['a', 'b', 'c', 'd', 'e'] [12, 34, 23, 11, 15]
Approach
- Loop over each dict’s items.
Solution
data = [{"a": 12}, {"b": 34}, {"c": 23}, {"d": 11}, {"e": 15}]keys = [k for d in data for k in d]values = [v for d in data for v in d.values()]print(keys)print(values)Output
['a', 'b', 'c', 'd', 'e'] [12, 34, 23, 11, 15]
Learn the concept
New to this topic? Read the lesson, then come back.