Split a dictionary into chunks

Split a dictionary into chunks

EasyDictionary Programs · 92 of 94

Write a Python program to split a dictionary into dictionaries of n items.

Input
{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}, n = 3
Output
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]

Approach

  1. Slice the list of items in steps of n.

Solution

Python
d = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}n = 3items = list(d.items())print([dict(items[i:i + n]) for i in range(0, len(items), n)])
Output
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Sort by the sum of list values

Sort by the sum of list values

EasyDictionary Programs · 91 of 94

Write a Python program to map each key to the sum of its list and sort by that sum.

Input
{"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}
Output
{'x': 12, 'c': 12, 'y': 14}

Approach

  1. Sum the lists, then sort by value.

Solution

Python
d = {"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}sums = {k: sum(v) for k, v in d.items()}print(dict(sorted(sums.items(), key=lambda kv: kv[1])))
Output
{'x': 12, 'c': 12, 'y': 14}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Sum of unique values across lists

Sum of unique values across lists

EasyDictionary Programs · 94 of 94

Write a Python program to add up the distinct numbers found in all list values.

Input
{"a": [6, 7, 2, 8, 1], "b": [2, 3, 1, 6, 8, 10], "d": [1, 8, 2, 6, 9]}
Output
[1, 2, 3, 6, 7, 8, 9, 10] 46

Approach

  1. Union of all values in a set, then sum.

Solution

Python
d = {"a": [6, 7, 2, 8, 1], "b": [2, 3, 1, 6, 8, 10], "d": [1, 8, 2, 6, 9]}unique = set().union(*d.values())print(sorted(unique), sum(unique))
Output
[1, 2, 3, 6, 7, 8, 9, 10] 46

Line by line

Line 2

set().union(*lists) merges all the lists into one set of distinct numbers.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Reverse values and decorate keys

Reverse values and decorate keys

EasyDictionary Programs · 93 of 94

Write a Python program to reverse each string value and put underscores around each key.

Input
{"a": "Python", "b": "Programming", "c": "Learning"}
Output
{'_a_': 'nohtyP', '_b_': 'gnimmargorP', '_c_': 'gninraeL'}

Approach

  1. Dict comprehension with an f-string key and [::-1] value.

Solution

Python
d = {"a": "Python", "b": "Programming", "c": "Learning"}print({f"_{k}_": v[::-1] for k, v in d.items()})
Output
{'_a_': 'nohtyP', '_b_': 'gnimmargorP', '_c_': 'gninraeL'}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

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