Depth of a nested dictionary

Depth of a nested dictionary

MediumDictionary Programs · 65 of 94

Write a Python program to find the depth of a nested dictionary.

Input
{"a": 1, "b": {"c": {"d": {}}}}
Output
4

Approach

  1. Depth is 1 plus the deepest child dictionary’s depth (recursion).

Solution

Python
def depth(d):    if not isinstance(d, dict) or not d:        return 1 if isinstance(d, dict) else 0    return 1 + max(depth(v) for v in d.values()) print(depth({"a": 1, "b": {"c": {"d": {}}}}))
Output
4

Line by line

Lines 2-3

An empty dict has depth 1; a non-dict value adds nothing.

Line 4

Each level adds 1 to the deepest value below it.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Length of each value

Length of each value

EasyDictionary Programs · 64 of 94

Write a Python program to map each string value to its length.

Input
{1: "sqa", 2: "tools", 3: "python"}
Output
{'sqa': 3, 'tools': 5, 'python': 6}

Approach

  1. {v: len(v) for v in d.values()}.

Solution

Python
d = {1: "sqa", 2: "tools", 3: "python"}print({v: len(v) for v in d.values()})
Output
{'sqa': 3, 'tools': 5, 'python': 6}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Values for one key from a list of dicts

Values for one key from a list of dicts

EasyDictionary Programs · 63 of 94

Write a Python program to extract the values for a key from a list of dictionaries.

Input
[{"t20": 50, "odi": 70}, {"t20": 40, "odi": 10}, {"t20": 30, "odi": 0}, {"t20": 45, "odi": 65}], key "odi"
Output
[70, 10, 0, 65]

Approach

  1. [d["odi"] for d in data].

Solution

Python
data = [{"t20": 50, "odi": 70}, {"t20": 40, "odi": 10}, {"t20": 30, "odi": 0}, {"t20": 45, "odi": 65}]print([d["odi"] for d in data])
Output
[70, 10, 0, 65]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Update list values

Update list values

EasyDictionary Programs · 62 of 94

Write a Python program to add 10 to every number in the first list and subtract 25 from the second.

Input
{"virat": [50, 30], "rohit": [40, 10]}
Output
{'virat': [60, 40], 'rohit': [15, -15]}

Approach

  1. Rebuild each list with a comprehension.

Solution

Python
d = {"virat": [50, 30], "rohit": [40, 10]}d["virat"] = [x + 10 for x in d["virat"]]d["rohit"] = [x - 25 for x in d["rohit"]]print(d)
Output
{'virat': [60, 40], 'rohit': [15, -15]}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Empty every list value

Empty every list value

EasyDictionary Programs · 61 of 94

Write a Python program to clear the list values in a dictionary.

Input
{"virat": [50, 30], "rohit": [40, 10]}
Output
{'virat': [], 'rohit': []}

Approach

  1. clear() each list in place.

Solution

Python
d = {"virat": [50, 30], "rohit": [40, 10]}for v in d.values():    v.clear()print(d)
Output
{'virat': [], 'rohit': []}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Convert string values to numbers

Convert string values to numbers

EasyDictionary Programs · 60 of 94

Write a Python program to convert the string values of a dictionary to int or float.

Input
{"a": "30", "b": "20", "c": "10"}, {"a": "3.33", "b": "20.50", "c": "12.5"}
Output
{'a': 30, 'b': 20, 'c': 10}
{'a': 3.33, 'b': 20.5, 'c': 12.5}

Approach

  1. Use int when the text has no decimal point, otherwise float.

Solution

Python
def to_number(text):    return float(text) if "." in text else int(text) for d in [{"a": "30", "b": "20", "c": "10"}, {"a": "3.33", "b": "20.50", "c": "12.5"}]:    print({k: to_number(v) for k, v in d.items()})
Output
{'a': 30, 'b': 20, 'c': 10}
{'a': 3.33, 'b': 20.5, 'c': 12.5}

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Remove a dictionary from a list

Remove a dictionary from a list

EasyDictionary Programs · 59 of 94

Write a Python program to remove the 4th dictionary from a list.

Input
[{"t20": 50, "odi": 70}, {"t20": 40, "odi": 10}, {"t20": 30, "odi": 0}, {"t20": 45, "odi": 65}]
Output
[{'t20': 50, 'odi': 70}, {'t20': 40, 'odi': 10}, {'t20': 30, 'odi': 0}]

Approach

  1. pop(3).

Solution

Python
data = [{"t20": 50, "odi": 70}, {"t20": 40, "odi": 10}, {"t20": 30, "odi": 0}, {"t20": 45, "odi": 65}]data.pop(3)print(data)
Output
[{'t20': 50, 'odi': 70}, {'t20': 40, 'odi': 10}, {'t20': 30, 'odi': 0}]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Dict of lists to list of dicts

Dict of lists to list of dicts

EasyDictionary Programs · 58 of 94

Write a Python program to split a dictionary of lists into a list of dictionaries.

Input
{"t20": [50, 40, 30, 45], "odi": [70, 10, 0, 65]}
Output
[{'t20': 50, 'odi': 70}, {'t20': 40, 'odi': 10}, {'t20': 30, 'odi': 0}, {'t20': 45, 'odi': 65}]

Approach

  1. zip(*d.values()) gives one row per position.

Solution

Python
d = {"t20": [50, 40, 30, 45], "odi": [70, 10, 0, 65]}print([dict(zip(d, row)) for row in zip(*d.values())])
Output
[{'t20': 50, 'odi': 70}, {'t20': 40, 'odi': 10}, {'t20': 30, 'odi': 0}, {'t20': 45, 'odi': 65}]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Group key-value pairs into lists

Group key-value pairs into lists

EasyDictionary Programs · 57 of 94

Write a Python program to group a sequence of (key, value) pairs into a dictionary of lists.

Input
[("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]
Output
{'virat': [50, 30], 'rohit': [40, 10]}

Approach

  1. defaultdict(list).

Solution

Python
from collections import defaultdict pairs = [("virat", 50), ("rohit", 40), ("virat", 30), ("rohit", 10)]groups = defaultdict(list)for k, v in pairs:    groups[k].append(v)print(dict(groups))
Output
{'virat': [50, 30], 'rohit': [40, 10]}
Note

A dict literal cannot hold the same key twice, so the input is a list of pairs.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Are all values the same?

Are all values the same?

EasyDictionary Programs · 56 of 94

Write a Python program to check whether all values in a dictionary are the same.

Input
{"virat": 50, "rohit": 50, "rahul": 50, "hardik": 50}
Output
True

Approach

  1. A set of the values has one item when they are all equal.

Solution

Python
d = {"virat": 50, "rohit": 50, "rahul": 50, "hardik": 50}print(len(set(d.values())) == 1)
Output
True

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs