Dictionary of lists to list of lists

Dictionary of lists to list of lists

EasyDictionary Programs · 43 of 94

Write a Python program to convert {key: [values]} into [[key, values…], …].

Input
{"sqa": [1, 4, 6], "tools": [3, 6, 9]}
Output
[['sqa', 1, 4, 6], ['tools', 3, 6, 9]]

Approach

  1. [k, *v] unpacks the list after the key.

Solution

Python
d = {"sqa": [1, 4, 6], "tools": [3, 6, 9]}print([[k, *v] for k, v in d.items()])
Output
[['sqa', 1, 4, 6], ['tools', 3, 6, 9]]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Print a nested dictionary line by line

Print a nested dictionary line by line

EasyDictionary Programs · 42 of 94

Write a Python program to print a nested dictionary line by line.

Input
{"virat": {"sport": "cricket", "team": "india"}, "messi": {"sport": "football", "team": "argentina"}}
Output
Virat
  Sport : cricket
  Team : india
Messi
  Sport : football
  Team : argentina

Approach

  1. An outer loop for players, an inner loop for their details.

Solution

Python
d = {"virat": {"sport": "cricket", "team": "india"},     "messi": {"sport": "football", "team": "argentina"}}for name, info in d.items():    print(name.title())    for key, value in info.items():        print(f"  {key.title()} : {value}")
Output
Virat
  Sport : cricket
  Team : india
Messi
  Sport : football
  Team : argentina

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Product with the highest price

Product with the highest price

EasyDictionary Programs · 41 of 94

Write a Python program to find the product with the highest price.

Input
{"price1": 450, "price2": 600, "price3": 255, "price4": 400}
Output
price2 600

Approach

  1. max(d, key=d.get).

Solution

Python
d = {"price1": 450, "price2": 600, "price3": 255, "price4": 400}best = max(d, key=d.get)print(best, d[best])
Output
price2 600
Note

The highest price is 600 for price2; the original sample output said 500.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

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