Initialise with default values

Initialise with default values

EasyDictionary Programs · 87 of 94

Write a Python program to give every name its own copy of a default settings dictionary.

Input
["Virat", "Rohit"], {"sport": "cricket", "salary": 100000}
Output
{'Virat': {'sport': 'cricket', 'salary': 100000}, 'Rohit': {'sport': 'cricket', 'salary': 120000}}

Approach

  1. Copy the defaults for each name.

Solution

Python
names = ["Virat", "Rohit"]defaults = {"sport": "cricket", "salary": 100000}players = {name: defaults.copy() for name in names}players["Rohit"]["salary"] = 120000print(players)
Output
{'Virat': {'sport': 'cricket', 'salary': 100000}, 'Rohit': {'sport': 'cricket', 'salary': 120000}}

Line by line

Line 3

.copy() gives each player an independent dict, so changing Rohit’s salary does not change Virat’s.

Watch out

dict.fromkeys(names, defaults) would share one dict between all names.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

List of all values

List of all values

EasyDictionary Programs · 86 of 94

Write a Python program to get a list of all values.

Input
{"sqa": 1, "tools": 2, "is": 2, "best": 4}
Output
[1, 2, 2, 4]

Approach

  1. list(d.values()).

Solution

Python
print(list({"sqa": 1, "tools": 2, "is": 2, "best": 4}.values()))
Output
[1, 2, 2, 4]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

List of all keys

List of all keys

EasyDictionary Programs · 85 of 94

Write a Python program to get a list of all keys.

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

Approach

  1. list(d).

Solution

Python
print(list({"sqa": [1, 2, 5, 6], "tools": [3, 8, 9], "is": [2, 5, 0], "best": [3, 6, 8]}))
Output
['sqa', 'tools', 'is', 'best']

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

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