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

Frequency of values

Frequency of values

EasyDictionary Programs · 74 of 94

Write a Python program to count how often each value appears in a dictionary.

Input
{"a": 10, "b": 20, "c": 25, "d": 10, "e": 30, "f": 20}
Output
{10: 2, 20: 2, 25: 1, 30: 1}

Approach

  1. Counter(d.values()).

Solution

Python
from collections import Counterd = {"a": 10, "b": 20, "c": 25, "d": 10, "e": 30, "f": 20}print(dict(Counter(d.values())))
Output
{10: 2, 20: 2, 25: 1, 30: 1}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Keys with the shortest lists

Keys with the shortest lists

EasyDictionary Programs · 73 of 94

Write a Python program to find the keys whose list values are the shortest.

Input
{"a": [10, 12], "b": [10], "c": [10, 20, 30, 40], "d": [20]}
Output
['b', 'd']

Approach

  1. Find the minimum length, then keep keys with that length.

Solution

Python
d = {"a": [10, 12], "b": [10], "c": [10, 20, 30, 40], "d": [20]}shortest = min(len(v) for v in d.values())print([k for k, v in d.items() if len(v) == shortest])
Output
['b', 'd']

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Keys of the top 2 values

Keys of the top 2 values

EasyDictionary Programs · 72 of 94

Write a Python program to find the keys of the two largest values.

Input
{"a": 18, "b": 50, "c": 36, "d": 47, "e": 60}
Output
['e', 'b']

Approach

  1. Sort keys by value, descending, and take two.

Solution

Python
d = {"a": 18, "b": 50, "c": 36, "d": 47, "e": 60}print(sorted(d, key=d.get, reverse=True)[:2])
Output
['e', 'b']

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Keep even numbers in list values

Keep even numbers in list values

EasyDictionary Programs · 71 of 94

Write a Python program to keep only even numbers in each list value.

Input
{"a": [11, 4, 6, 15], "b": [3, 8, 12], "c": [5, 3, 10]}
Output
{'a': [4, 6], 'b': [8, 12], 'c': [10]}

Approach

  1. Nested comprehensions.

Solution

Python
d = {"a": [11, 4, 6, 15], "b": [3, 8, 12], "c": [5, 3, 10]}print({k: [x for x in v if x % 2 == 0] for k, v in d.items()})
Output
{'a': [4, 6], 'b': [8, 12], 'c': [10]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Print the keys

Print the keys

EasyDictionary Programs · 70 of 94

Write a Python program to print the keys of a dictionary, capitalised.

Input
{"pepsi": 50, "sprite": 60, "slice": 55}
Output
Pepsi
Sprite
Slice

Approach

  1. Loop over the dict.

Solution

Python
drinks = {"pepsi": 50, "sprite": 60, "slice": 55}for name in drinks:    print(name.title())
Output
Pepsi
Sprite
Slice

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Remove keys whose values contain a substring

Remove keys whose values contain a substring

EasyDictionary Programs · 69 of 94

Write a Python program to remove entries whose value contains any of the given substrings.

Input
{1: "sqatools is best", 2: "for learning python"}, ["best", "excellent"]
Output
{2: 'for learning python'}

Approach

  1. Keep values where no substring is present.

Solution

Python
d = {1: "sqatools is best", 2: "for learning python"}subs = ["best", "excellent"]print({k: v for k, v in d.items() if not any(s in v for s in subs)})
Output
{2: 'for learning python'}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Remove keys with large values

Remove keys with large values

EasyDictionary Programs · 68 of 94

Write a Python program to remove keys whose values are greater than n.

Input
{"sqa": 3, "tools": 5, "python": 7}, n = 6
Output
{'sqa': 3, 'tools': 5}

Approach

  1. Keep v <= n.

Solution

Python
d = {"sqa": 3, "tools": 5, "python": 7}n = 6print({k: v for k, v in d.items() if v <= n})
Output
{'sqa': 3, 'tools': 5}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs