Sort the list values

Sort the list values

EasyDictionary Programs · 40 of 94

Write a Python program to sort each list value of a dictionary.

Input
{"a1": [1, 5, 3], "a2": [10, 6, 20]}
Output
{'a1': [1, 3, 5], 'a2': [6, 10, 20]}

Approach

  1. {k: sorted(v) ...}.

Solution

Python
d = {"a1": [1, 5, 3], "a2": [10, 6, 20]}print({k: sorted(v) for k, v in d.items()})
Output
{'a1': [1, 3, 5], 'a2': [6, 10, 20]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

List to a nested dictionary

List to a nested dictionary

MediumDictionary Programs · 39 of 94

Write a Python program to convert a list into a nested dictionary of keys.

Input
["a", "b", "c", "d"]
Output
{'a': {'b': {'c': {'d': {}}}}}

Approach

  1. Build from the inside out: start with {} and wrap it for each key in reverse.

Solution

Python
keys = ["a", "b", "c", "d"]nested = {}for key in reversed(keys):    nested = {key: nested}print(nested)
Output
{'a': {'b': {'c': {'d': {}}}}}

Line by line

Lines 3-4

Starting from “d” and wrapping outwards gives {“a”: {“b”: {“c”: {“d”: {}}}}}.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Mean of dictionary values

Mean of dictionary values

EasyDictionary Programs · 38 of 94

Write a Python program to find the mean of a dictionary’s values.

Input
{"m1": 25, "m2": 20, "m3": 15}
Output
Mean is 20.0

Approach

  1. sum / len.

Solution

Python
d = {"m1": 25, "m2": 20, "m3": 15}print("Mean is", sum(d.values()) / len(d))
Output
Mean is 20.0

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Count frequencies in a list

Count frequencies in a list

EasyDictionary Programs · 37 of 94

Write a Python program to count how often each item appears in a list, using a dictionary.

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

Approach

  1. get(x, 0) + 1, then sort by key.

Solution

Python
items = [2, 5, 8, 1, 2, 6, 8, 5]freq = {}for x in items:    freq[x] = freq.get(x, 0) + 1print(dict(sorted(freq.items())))
Output
{1: 1, 2: 2, 5: 2, 6: 1, 8: 2}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Print a dictionary as a table

Print a dictionary as a table

EasyDictionary Programs · 36 of 94

Write a Python program to print a dictionary of lists as a table.

Input
{"names": ["virat", "messi", "kobe"], "sport": ["cricket", "football", "basketball"]}
Output
   Names       Sport       
0  Virat       Cricket     
1  Messi       Football    
2  Kobe        Basketball  

Approach

  1. Print a header, then zip the columns into rows.

Solution

Python
d = {"names": ["virat", "messi", "kobe"], "sport": ["cricket", "football", "basketball"]}print(f"{'':3}" + "".join(f"{h.title():<12}" for h in d))for i, row in enumerate(zip(*d.values())):    print(f"{i:<3}" + "".join(f"{cell.title():<12}" for cell in row))
Output
   Names       Sport       
0  Virat       Cricket     
1  Messi       Football    
2  Kobe        Basketball  

Line by line

Line 3

zip(*d.values()) turns the column lists into rows.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Letter frequency with Counter

Letter frequency with Counter

EasyDictionary Programs · 35 of 94

Write a Python program to create a dictionary of letter counts from a string.

Input
"sqatools"
Output
{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}

Approach

  1. Counter(text).

Solution

Python
from collections import Counterprint(dict(Counter("sqatools")))
Output
{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Letter combinations from values

Letter combinations from values

EasyDictionary Programs · 34 of 94

Write a Python program to print every combination of one letter from each dictionary value.

Input
{"x": ["e", "f"], "y": ["a", "b"]}
Output
ea
eb
fa
fb

Approach

  1. itertools.product(*d.values()).

Solution

Python
from itertools import product d = {"x": ["e", "f"], "y": ["a", "b"]}for combo in product(*d.values()):    print("".join(combo))
Output
ea
eb
fa
fb

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Unique values in a list of dicts

Unique values in a list of dicts

EasyDictionary Programs · 33 of 94

Write a Python program to print the unique values from a list of dictionaries.

Input
[{"name1": "robert"}, {"name2": "john"}, {"name3": "jim"}, {"name4": "robert"}]
Output
['robert', 'john', 'jim']

Approach

  1. Collect values in order and remove duplicates with dict.fromkeys.

Solution

Python
data = [{"name1": "robert"}, {"name2": "john"}, {"name3": "jim"}, {"name4": "robert"}]values = [v for d in data for v in d.values()]print(list(dict.fromkeys(values)))
Output
['robert', 'john', 'jim']

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Add values of matching keys

Add values of matching keys

EasyDictionary Programs · 32 of 94

Write a Python program to combine two dictionaries, adding the values of keys that appear in both.

Input
{"x": 10, "y": 20, "c": 50, "f": 44}, {"x": 60, "c": 25, "y": 56}
Output
{'x': 70, 'y': 76, 'c': 75, 'f': 44}
True

Approach

  1. Start with a copy of the first dict and add the second’s values with get.

Solution

Python
d1 = {"x": 10, "y": 20, "c": 50, "f": 44}d2 = {"x": 60, "c": 25, "y": 56}total = d1.copy()for k, v in d2.items():    total[k] = total.get(k, 0) + vprint(total) from collections import Counterprint(dict(Counter(d1) + Counter(d2)) == total)
Output
{'x': 70, 'y': 76, 'c': 75, 'f': 44}
True

Line by line

Line 5

Keys only in d2 start from 0.

Line 8

Counter addition does the same for positive values.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Is a dictionary empty?

Is a dictionary empty?

EasyDictionary Programs · 31 of 94

Write a Python program to check whether a dictionary is empty.

Input
{}, {"a": 1}
Output
{} -> empty
{'a': 1} -> not empty

Approach

  1. An empty dict is falsy.

Solution

Python
for d in [{}, {"a": 1}]:    print(d, "-> empty" if not d else "-> not empty")
Output
{} -> empty
{'a': 1} -> not empty

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs