Invert a dictionary with repeated values

Invert a dictionary with repeated values

EasyDictionary Programs · 90 of 94

Write a Python program to invert a dictionary whose values repeat, collecting keys in lists.

Input
{"alex": 1, "bob": 2, "martin": 1, "robert": 2}
Output
{1: ['alex', 'martin'], 2: ['bob', 'robert']}

Approach

  1. setdefault(v, []).append(k).

Solution

Python
d = {"alex": 1, "bob": 2, "martin": 1, "robert": 2}inverted = {}for k, v in d.items():    inverted.setdefault(v, []).append(k)print(inverted)
Output
{1: ['alex', 'martin'], 2: ['bob', 'robert']}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Rename a key

Rename a key

EasyDictionary Programs · 89 of 94

Write a Python program to rename the key “d” to “e”.

Input
{"a": 19, "b": 20, "c": 21, "d": 20}
Output
{'a': 19, 'b': 20, 'c': 21, 'e': 20}

Approach

  1. d["e"] = d.pop("d").

Solution

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

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Delete several keys

Delete several keys

EasyDictionary Programs · 88 of 94

Write a Python program to delete a list of keys from a dictionary.

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

Approach

  1. pop(k, None) for each key.

Solution

Python
d = {"a": 19, "b": 20, "c": 21, "d": 20, "e": 50}for k in ["a", "d", "e"]:    d.pop(k, None)print(d)
Output
{'b': 20, 'c': 21}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

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