Group key-value pairs into lists

Group key-value pairs into lists

EasyDictionary Programs · 57 of 94

Write a Python program to group a sequence of (key, value) pairs into a dictionary of lists.

Input
[("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]
Output
{'virat': [50, 30], 'rohit': [40, 10]}

Approach

  1. defaultdict(list).

Solution

Python
from collections import defaultdict pairs = [("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]groups = defaultdict(list)for k, v in pairs:    groups[k].append(v)print(dict(groups))
Output
{'virat': [50, 30], 'rohit': [40, 10]}
Note

A dict literal cannot hold the same key twice, so the input is a list of pairs.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Are all values the same?

Are all values the same?

EasyDictionary Programs · 56 of 94

Write a Python program to check whether all values in a dictionary are the same.

Input
{"virat": 50, "rohit": 50, "rahul": 50, "hardik": 50}
Output
True

Approach

  1. A set of the values has one item when they are all equal.

Solution

Python
d = {"virat": 50, "rohit": 50, "rahul": 50, "hardik": 50}print(len(set(d.values())) == 1)
Output
True

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Matrix rows to a dictionary

Matrix rows to a dictionary

EasyDictionary Programs · 55 of 94

Write a Python program to convert a matrix into a dictionary keyed by row number.

Input
[[1, 2, 3], [4, 5, 6]]
Output
{1: [1, 2, 3], 2: [4, 5, 6]}

Approach

  1. enumerate(matrix, start=1).

Solution

Python
matrix = [[1, 2, 3], [4, 5, 6]]print(dict(enumerate(matrix, start=1)))
Output
{1: [1, 2, 3], 2: [4, 5, 6]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

String to a dictionary

String to a dictionary

EasyDictionary Programs · 54 of 94

Write a Python program to convert “key=value; key=value” text into a dictionary.

Input
"Apr=April; Mar=March"
Output
{'Apr': 'April', 'Mar': 'March'}

Approach

  1. Split on “;”, then split each part on “=” and strip spaces.

Solution

Python
text = "Apr=April; Mar=March"d = dict(part.strip().split("=") for part in text.split(";"))print(d)
Output
{'Apr': 'April', 'Mar': 'March'}

Line by line

Line 2

strip() removes the space after each semicolon, so the second key is “Mar”, not ” Mar”.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

List of tuples to a dictionary

List of tuples to a dictionary

EasyDictionary Programs · 53 of 94

Write a Python program to convert a list of pairs into a dictionary.

Input
[("mike", 1), ("Sarah", 20), ("Jim", 16)]
Output
{'mike': 1, 'Sarah': 20, 'Jim': 16}

Approach

  1. dict(pairs).

Solution

Python
print(dict([("mike", 1), ("Sarah", 20), ("Jim", 16)]))
Output
{'mike': 1, 'Sarah': 20, 'Jim': 16}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Two lists in a dict to one flat dict

Two lists in a dict to one flat dict

EasyDictionary Programs · 52 of 94

Write a Python program to pair the two list values of a dictionary into a flat dictionary.

Input
{"name": ["Apr", "May", "June"], "month": [4, 5, 6]}
Output
{'Apr': 4, 'May': 5, 'June': 6}

Approach

  1. zip the two lists.

Solution

Python
d = {"name": ["Apr", "May", "June"], "month": [4, 5, 6]}print(dict(zip(d["name"], d["month"])))
Output
{'Apr': 4, 'May': 5, 'June': 6}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Filter by value

Filter by value

EasyDictionary Programs · 51 of 94

Write a Python program to keep entries with values greater than 40.

Input
{"alex": 50, "john": 45, "Robert": 30}
Output
{'alex': 50, 'john': 45}

Approach

  1. Dict comprehension with a condition.

Solution

Python
d = {"alex": 50, "john": 45, "Robert": 30}print({k: v for k, v in d.items() if v > 40})
Output
{'alex': 50, 'john': 45}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Drop empty items

Drop empty items

EasyDictionary Programs · 50 of 94

Write a Python program to drop items whose value is None.

Input
{"m1": 40, "m2": 50, "m3": None}
Output
{'m1': 40, 'm2': 50}

Approach

  1. Keep pairs where v is not None.

Solution

Python
d = {"m1": 40, "m2": 50, "m3": None}print({k: v for k, v in d.items() if v is not None})
Output
{'m1': 40, 'm2': 50}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Keys a, b, c with ranges

Keys a, b, c with ranges

EasyDictionary Programs · 49 of 94

Write a Python program to create {“a”: 1-5, “b”: 6-10, “c”: 11-15} as lists.

Output
{'a': [1, 2, 3, 4, 5], 'b': [6, 7, 8, 9, 10], 'c': [11, 12, 13, 14, 15]}

Approach

  1. Each key’s list starts 5 higher than the previous.

Solution

Python
print({key: list(range(1 + 5 * i, 6 + 5 * i)) for i, key in enumerate("abc")})
Output
{'a': [1, 2, 3, 4, 5], 'b': [6, 7, 8, 9, 10], 'c': [11, 12, 13, 14, 15]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Matching key-value pairs

Matching key-value pairs

EasyDictionary Programs · 48 of 94

Write a Python program to find key-value pairs present in both dictionaries.

Input
{"k1": "p", "k2": "q", "k3": "r"}, {"k1": "p", "k2": "s"}
Output
k1: p is present in both a and b

Approach

  1. items() views support &.

Solution

Python
a = {"k1": "p", "k2": "q", "k3": "r"}b = {"k1": "p", "k2": "s"}for k, v in a.items() & b.items():    print(f"{k}: {v} is present in both a and b")
Output
k1: p is present in both a and b

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs