Sort a dictionary by value

Sort a dictionary by value

EasyDictionary Programs · 12 of 94

Write a Python program to sort a dictionary by its values.

Input
{"d": 14, "b": 52, "a": 13, "c": 1}
Output
[('c', 1), ('a', 13), ('d', 14), ('b', 52)]
{'b': 52, 'd': 14, 'a': 13, 'c': 1}

Approach

  1. key=lambda kv: kv[1].

Solution

Python
d = {"d": 14, "b": 52, "a": 13, "c": 1}print(sorted(d.items(), key=lambda kv: kv[1]))print(dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True)))
Output
[('c', 1), ('a', 13), ('d', 14), ('b', 52)]
{'b': 52, 'd': 14, 'a': 13, 'c': 1}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Sort a dictionary by key

Sort a dictionary by key

EasyDictionary Programs · 11 of 94

Write a Python program to sort a dictionary by its keys.

Input
{"d": 21, "b": 53, "a": 13, "c": 41}
Output
('a', 13)
('b', 53)
('c', 41)
('d', 21)
{'a': 13, 'b': 53, 'c': 41, 'd': 21}

Approach

  1. sorted(d.items()) sorts the pairs by key.

Solution

Python
d = {"d": 21, "b": 53, "a": 13, "c": 41}for pair in sorted(d.items()):    print(pair)print(dict(sorted(d.items())))
Output
('a', 13)
('b', 53)
('c', 41)
('d', 21)
{'a': 13, 'b': 53, 'c': 41, 'd': 21}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Character counts of a string

Character counts of a string

EasyDictionary Programs · 10 of 94

Write a Python program to build a dictionary of character counts from a string.

Input
"SQATools"
Output
{'S': 1, 'Q': 1, 'A': 1, 'T': 1, 'o': 2, 'l': 1, 's': 1}

Approach

  1. get(ch, 0) + 1 for each character.

Solution

Python
text = "SQATools"counts = {}for ch in text:    counts[ch] = counts.get(ch, 0) + 1print(counts)
Output
{'S': 1, 'Q': 1, 'A': 1, 'T': 1, 'o': 2, 'l': 1, 's': 1}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Remove duplicate values

Remove duplicate values

EasyDictionary Programs · 9 of 94

Write a Python program to keep only the first key for each distinct value.

Input
{"a": 12, "b": 2, "c": 12, "d": 5, "e": 35, "f": 5}
Output
{'a': 12, 'b': 2, 'd': 5, 'e': 35}

Approach

  1. Remember the values seen while copying items.

Solution

Python
d = {"a": 12, "b": 2, "c": 12, "d": 5, "e": 35, "f": 5}seen = set()result = {}for k, v in d.items():    if v not in seen:        seen.add(v)        result[k] = vprint(result)
Output
{'a': 12, 'b': 2, 'd': 5, 'e': 35}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Clear a dictionary

Clear a dictionary

EasyDictionary Programs · 8 of 94

Write a Python program to remove all items from a dictionary.

Input
{"a": 1, "b": 2}
Output
{} {}

Approach

  1. clear() empties the same object.

Solution

Python
d = {"a": 1, "b": 2}alias = dd.clear()print(d, alias)
Output
{} {}

Line by line

Line 3

clear empties the dict itself, so every name pointing to it sees the change. d = {} would only rebind d.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Squares of even, cubes of odd

Squares of even, cubes of odd

EasyDictionary Programs · 7 of 94

Write a Python program that stores squares of even numbers and cubes of odd numbers in a dictionary using a comprehension.

Input
[4, 5, 6, 2, 1, 7, 11]
Output
{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}

Approach

  1. A conditional expression picks the power.

Solution

Python
numbers = [4, 5, 6, 2, 1, 7, 11]print({n: n ** 2 if n % 2 == 0 else n ** 3 for n in numbers})
Output
{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Dictionary from two lists

Dictionary from two lists

EasyDictionary Programs · 6 of 94

Write a Python program to create a dictionary from a list of keys and a list of values.

Input
["a", "b", "c", "d", "e"], [12, 23, 24, 25, 15, 16]
Output
{'a': 12, 'b': 23, 'c': 24, 'd': 25, 'e': 15}

Approach

  1. dict(zip(keys, values)); zip stops at the shorter list.

Solution

Python
keys = ["a", "b", "c", "d", "e"]values = [12, 23, 24, 25, 15, 16]print(dict(zip(keys, values)))
Output
{'a': 12, 'b': 23, 'c': 24, 'd': 25, 'e': 15}

Line by line

Line 3

The extra value 16 is ignored because zip stops when the shorter list ends.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Odd and even keys

Odd and even keys

EasyDictionary Programs · 5 of 94

Write a Python program to get lists of the items with even keys and with odd keys.

Input
{1: 25, 5: "abc", 8: "pqr", 21: "xyz", 12: "def", 2: "utv"}
Output
Even Key = [[8, 'pqr'], [12, 'def'], [2, 'utv']]
Odd Key = [[1, 25], [5, 'abc'], [21, 'xyz']]

Approach

  1. Filter items() by key % 2.

Solution

Python
d = {1: 25, 5: "abc", 8: "pqr", 21: "xyz", 12: "def", 2: "utv"}even = [[k, v] for k, v in d.items() if k % 2 == 0]odd = [[k, v] for k, v in d.items() if k % 2 == 1]print("Even Key =", even)print("Odd Key =", odd)
Output
Even Key = [[8, 'pqr'], [12, 'def'], [2, 'utv']]
Odd Key = [[1, 25], [5, 'abc'], [21, 'xyz']]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Concatenate two dictionaries

Concatenate two dictionaries

EasyDictionary Programs · 4 of 94

Write a Python program to concatenate two dictionaries.

Input
{"Name": "Harry", "Rollno": 345, "Address": "Jordan"}, {"Age": 25, "salary": "$25k"}
Output
{'Name': 'Harry', 'Rollno': 345, 'Address': 'Jordan', 'Age': 25, 'salary': '$25k'}
{'Name': 'Harry', 'Rollno': 345, 'Address': 'Jordan', 'Age': 25, 'salary': '$25k'}

Approach

  1. | (Python 3.9+) creates a merged dict; update changes one in place.

Solution

Python
dict1 = {"Name": "Harry", "Rollno": 345, "Address": "Jordan"}dict2 = {"Age": 25, "salary": "$25k"}print(dict1 | dict2)dict1.update(dict2)print(dict1)
Output
{'Name': 'Harry', 'Rollno': 345, 'Address': 'Jordan', 'Age': 25, 'salary': '$25k'}
{'Name': 'Harry', 'Rollno': 345, 'Address': 'Jordan', 'Age': 25, 'salary': '$25k'}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Move items to another dictionary

Move items to another dictionary

EasyDictionary Programs · 3 of 94

Write a Python program to move all items from dict1 to dict2, leaving dict1 empty.

Input
{"name": "john", "city": "London", "country": "UK"}
Output
dict1 = {}
dict2 = {'name': 'john', 'city': 'London', 'country': 'UK'}

Approach

  1. update dict2, then clear dict1.

Solution

Python
dict1 = {"name": "john", "city": "London", "country": "UK"}dict2 = {}dict2.update(dict1)dict1.clear()print("dict1 =", dict1)print("dict2 =", dict2)
Output
dict1 = {}
dict2 = {'name': 'john', 'city': 'London', 'country': 'UK'}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs