Dictionary to a list of tuples

Dictionary to a list of tuples

EasyDictionary Programs · 84 of 94

Write a Python program to convert a dictionary to a list of (key, value) tuples.

Input
{"a": 19, "b": 20, "c": 21, "d": 20}
Output
[('a', 19), ('b', 20), ('c', 21), ('d', 20)]

Approach

  1. list(d.items()).

Solution

Python
print(list({"a": 19, "b": 20, "c": 21, "d": 20}.items()))
Output
[('a', 19), ('b', 20), ('c', 21), ('d', 20)]

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Keys with a given value

Keys with a given value

EasyDictionary Programs · 83 of 94

Write a Python program to find all keys that have a given value.

Input
{"a": 19, "b": 20, "c": 21, "d": 20}, value 20
Output
['b', 'd']

Approach

  1. Filter items().

Solution

Python
d = {"a": 19, "b": 20, "c": 21, "d": 20}print([k for k, v in d.items() if v == 20])
Output
['b', 'd']

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Values of one key from many dicts

Values of one key from many dicts

EasyDictionary Programs · 82 of 94

Write a Python program to get the values of a key from a list of dictionaries.

Input
[{"name": "jos", "age": 30}, {"name": "david", "age": 25}, {"name": "virat", "age": 32}], key "age"
Output
[30, 25, 32]

Approach

  1. A comprehension.

Solution

Python
data = [{"name": "jos", "age": 30}, {"name": "david", "age": 25}, {"name": "virat", "age": 32}]print([d["age"] for d in data])
Output
[30, 25, 32]

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Which keys contain each value

Which keys contain each value

EasyDictionary Programs · 81 of 94

Write a Python program to show, for each value, the keys whose lists contain it.

Input
{"xyz": [20, 40], "abc": [10, 20]}
Output
{20: ['xyz', 'abc'], 40: ['xyz'], 10: ['abc']}

Approach

  1. Invert into defaultdict(list).

Solution

Python
from collections import defaultdict d = {"xyz": [20, 40], "abc": [10, 20]}inverted = defaultdict(list)for key, values in d.items():    for v in values:        inverted[v].append(key)print(dict(inverted))
Output
{20: ['xyz', 'abc'], 40: ['xyz'], 10: ['abc']}

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Unique values from list values

Unique values from list values

EasyDictionary Programs · 80 of 94

Write a Python program to extract the unique values from all list values, sorted.

Input
{"sqa": [1, 2, 5, 6], "tools": [3, 8, 9], "is": [2, 5, 0], "best": [3, 6, 8]}
Output
[0, 1, 2, 3, 5, 6, 8, 9]

Approach

  1. A set comprehension, then sort.

Solution

Python
d = {"sqa": [1, 2, 5, 6], "tools": [3, 8, 9], "is": [2, 5, 0], "best": [3, 6, 8]}print(sorted({x for v in d.values() for x in v}))
Output
[0, 1, 2, 3, 5, 6, 8, 9]

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Dictionary with the most keys

Dictionary with the most keys

EasyDictionary Programs · 79 of 94

Write a Python program to find which of two dictionaries has more keys.

Input
{"name": 1, "age": 2}, {"name": 1, "age": 2, "course": 3, "institute": 4}
Output
2nd dictionary has maximum keys, 4

Approach

  1. Compare len().

Solution

Python
a = {"name": 1, "age": 2}b = {"name": 1, "age": 2, "course": 3, "institute": 4}bigger = max([("1st", a), ("2nd", b)], key=lambda p: len(p[1]))print(f"{bigger[0]} dictionary has maximum keys, {len(bigger[1])}")
Output
2nd dictionary has maximum keys, 4

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Value at a nested path

Value at a nested path

MediumDictionary Programs · 78 of 94

Write a Python program to get the value at a path of keys and indexes in nested data.

Input
{"p1": {"name": {"first": "lionel", "last": "messi"}, "team": ["psg", "argentina"]}}
Output
Messi
Argentina

Approach

  1. Follow the path one step at a time with functools.reduce.

Solution

Python
from functools import reduce data = {"p1": {"name": {"first": "lionel", "last": "messi"}, "team": ["psg", "argentina"]}} def get_path(obj, path):    return reduce(lambda acc, key: acc[key], path, obj) print(get_path(data, ["p1", "name", "last"]).title())print(get_path(data, ["p1", "team", 1]).title())
Output
Messi
Argentina

Line by line

Lines 5-6

reduce applies acc[key] for each key in turn, starting from the whole object; indexes work for lists.

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Group a list by a function

Group a list by a function

EasyDictionary Programs · 77 of 94

Write a Python program to group the elements of a list by the result of a function such as len.

Input
["abc", "defg", "hijkl"]
Output
{3: ['abc'], 4: ['defg'], 5: ['hijkl']}
{'odd': [1, 3, 5], 'even': [2, 4]}

Approach

  1. defaultdict(list) keyed by func(item).

Solution

Python
from collections import defaultdict def group_by(items, func):    groups = defaultdict(list)    for x in items:        groups[func(x)].append(x)    return dict(groups) print(group_by(["abc", "defg", "hijkl"], len))print(group_by([1, 2, 3, 4, 5], lambda n: "even" if n % 2 == 0 else "odd"))
Output
{3: ['abc'], 4: ['defg'], 5: ['hijkl']}
{'odd': [1, 3, 5], 'even': [2, 4]}

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Total length of string keys

Total length of string keys

EasyDictionary Programs · 76 of 94

Write a Python program to count the number of keys and the total characters in them.

Input
{"virat": 50, "Rohit": 40, "Rahul": 25}
Output
Keys: 3
Total length of keys: 15

Approach

  1. len(d) for keys, sum(len(k) ...) for characters.

Solution

Python
d = {"virat": 50, "Rohit": 40, "Rahul": 25}print("Keys:", len(d))print("Total length of keys:", sum(len(k) for k in d))
Output
Keys: 3
Total length of keys: 15

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Pair keys with their single list item

Pair keys with their single list item

EasyDictionary Programs · 75 of 94

Write a Python program to turn {key: [value]} into one dictionary per combination.

Input
{1: ["Virat Kohli"], 2: ["Rohit Sharma"], 3: ["Hardik Pandya"]}
Output
[{1: 'Virat Kohli', 2: 'Rohit Sharma', 3: 'Hardik Pandya'}]

Approach

  1. itertools.product over the value lists, zipped back with the keys.

Solution

Python
from itertools import product d = {1: ["Virat Kohli"], 2: ["Rohit Sharma"], 3: ["Hardik Pandya"]}print([dict(zip(d, combo)) for combo in product(*d.values())])
Output
[{1: 'Virat Kohli', 2: 'Rohit Sharma', 3: 'Hardik Pandya'}]

Line by line

Line 4

With one item per list there is exactly one combination; longer lists would produce every pairing.

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs