Python Practice › List Programs › Program 35

Keys and values from a list of dicts

EasyList Programs · 35 of 100

Write a Python program to get all keys and all values from a list of single-item dictionaries.

Advertisement
Input
[{"a": 12}, {"b": 34}, {"c": 23}, {"d": 11}, {"e": 15}]
Output
['a', 'b', 'c', 'd', 'e']
[12, 34, 23, 11, 15]

Approach

  1. Loop over each dict’s items.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment