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

Group equal items

Group equal items

EasyDictionary Programs · 27 of 94

Write a Python program to group equal items of a list into dictionary values.

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

Approach

  1. setdefault(x, []).append(x), then sort by key.

Solution

Python
items = [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]groups = {}for x in items:    groups.setdefault(x, []).append(x)print(dict(sorted(groups.items())))
Output
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4], 5: [5, 5, 5]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Max and min values

Max and min values

EasyDictionary Programs · 26 of 94

Write a Python program to find the maximum and minimum values of a dictionary, with their keys.

Input
{"a": 10, "b": 44, "c": 60, "d": 25}
Output
Maximum value: 60 at key c
Minimum value: 10 at key a

Approach

  1. max(d, key=d.get) returns the key with the largest value.

Solution

Python
d = {"a": 10, "b": 44, "c": 60, "d": 25}print("Maximum value:", max(d.values()), "at key", max(d, key=d.get))print("Minimum value:", min(d.values()), "at key", min(d, key=d.get))
Output
Maximum value: 60 at key c
Minimum value: 10 at key a

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Map two lists to a dictionary

Map two lists to a dictionary

EasyDictionary Programs · 25 of 94

Write a Python program to map a list of keys to a list of values.

Input
["name", "sport", "rank", "age"], ["Virat", "cricket", 1, 32]
Output
{'name': 'Virat', 'sport': 'cricket', 'rank': 1, 'age': 32}

Approach

  1. dict(zip(...)).

Solution

Python
keys = ["name", "sport", "rank", "age"]values = ["Virat", "cricket", 1, 32]print(dict(zip(keys, values)))
Output
{'name': 'Virat', 'sport': 'cricket', 'rank': 1, 'age': 32}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Remove a key

Remove a key

EasyDictionary Programs · 24 of 94

Write a Python program to remove a key from a dictionary.

Input
{"a": 2, "b": 4, "c": 5}, remove "c"
Output
5 {'a': 2, 'b': 4}
not found

Approach

  1. pop(key, default) removes safely; del raises KeyError for a missing key.

Solution

Python
d = {"a": 2, "b": 4, "c": 5}removed = d.pop("c")print(removed, d)print(d.pop("zzz", "not found"))
Output
5 {'a': 2, 'b': 4}
not found

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs