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

Keep values that appear once in each list

Keep values that appear once in each list

EasyDictionary Programs · 30 of 94

Write a Python program to remove every value that is repeated inside each list value.

Input
{"marks1": [23, 28, 23, 69], "marks2": [25, 14, 25]}
Output
{'marks1': [28, 69], 'marks2': [14]}

Approach

  1. For each list keep items whose count is 1.

Solution

Python
d = {"marks1": [23, 28, 23, 69], "marks2": [25, 14, 25]}print({k: [x for x in v if v.count(x) == 1] for k, v in d.items()})
Output
{'marks1': [28, 69], 'marks2': [14]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Remove words that are dictionary keys

Remove words that are dictionary keys

EasyDictionary Programs · 29 of 94

Write a Python program to remove words from a string if they are keys in a dictionary.

Input
"sqatools is best for learning python", {"best": 2, "learning": 6}
Output
sqatools is for python

Approach

  1. Keep words that are not keys.

Solution

Python
text = "sqatools is best for learning python"d = {"best": 2, "learning": 6}print(" ".join(w for w in text.split() if w not in d))
Output
sqatools is for python

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Replace words using a dictionary

Replace words using a dictionary

EasyDictionary Programs · 28 of 94

Write a Python program to replace words in a string using a dictionary of replacements.

Input
"learning python at sqa-tools", {"at": "is", "sqa-tools": "fun"}
Output
learning python is fun

Approach

  1. Map each word through d.get(word, word).

Solution

Python
text = "learning python at sqa-tools"repl = {"at": "is", "sqa-tools": "fun"}print(" ".join(repl.get(w, w) for w in text.split()))
Output
learning python is fun

Line by line

Line 3

get(w, w) returns the replacement, or the word itself when there is none.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs