Rename key in nested dictionary Python

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations. All questions are tested on Python 3.

Python dictionary is a mutable object, and it contains the data in the form of key-value pairs. Each key is separated from its value by a colon (

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)
2).

Dictionary is the most widely used data structure, and it is necessary to understand its methods and operations.

Also Read:

  • Python Dictionary
  • Python Dictionary Quiz

This Python dictionary exercise includes the following: –

  • It contains 10 dictionary questions and solutions provided for each question.
  • Practice different dictionary assignments, programs, and challenges.

It covers questions on the following topics:

  • Dictionary operations and manipulations
  • Dictionary functions
  • Dictionary comprehension

When you complete each question, you get more familiar with the Python dictionary. Let us know if you have any alternative solutions. It will help other developers.

  • Use Online Code Editor to solve exercise questions.
  • Read the complete guide to Python dictionaries to solve this exercise

Table of contents

Exercise 1: Convert two lists into a dictionary

Below are the two lists. Write a Python program to convert them into a dictionary in a way that item from list1 is the key and item from list2 is the value

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

Expected output:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}

Show Hint

Use the

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)
3 function. This function takes two or more iterables (like list, dict, string), aggregates them in a tuple, and returns it.

Or, Iterate the list using a for loop and range() function. In each iteration, add a new key-value pair to a dict using the

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)
4 method

Show Solution

Solution 1: The zip() function and a

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)
5 constructor

  • Use the
    keys = ['Ten', 'Twenty', 'Thirty']
    values = [10, 20, 30]
    
    # empty dictionary
    res_dict = dict()
    
    for i in range(len(keys)):
        res_dict.update({keys[i]: values[i]})
    print(res_dict)
    
    6 to aggregate two lists.
  • Wrap the result of a
    keys = ['Ten', 'Twenty', 'Thirty']
    values = [10, 20, 30]
    
    # empty dictionary
    res_dict = dict()
    
    for i in range(len(keys)):
        res_dict.update({keys[i]: values[i]})
    print(res_dict)
    
    3 function into a
    keys = ['Ten', 'Twenty', 'Thirty']
    values = [10, 20, 30]
    
    # empty dictionary
    res_dict = dict()
    
    for i in range(len(keys)):
        res_dict.update({keys[i]: values[i]})
    print(res_dict)
    
    5 constructor.
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

res_dict = dict(zip(keys, values))
print(res_dict)

Solution 2: Using a loop and

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)
4 method of a dictionary

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)

Exercise 2: Merge two Python dictionaries into one

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

Expected output:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

Show Solution

Python 3.5+

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = {**dict1, **dict2}
print(dict3)

Other Versions

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)

Exercise 3: Print the value of key ‘history’ from the below dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30} dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}0

sampleDict = {
    "class": {
        "student": {
            "name": "Mike",
            "marks": {
                "physics": 70,
                "history": 80
            }
        }
    }
}

Expected output:

80

Show Hint

It is a nested dict. Use the correct chaining of keys to locate the specified key-value pair.

Show Solution

sampleDict = {
    "class": {
        "student": {
            "name": "Mike",
            "marks": {
                "physics": 70,
                "history": 80
            }
        }
    }
}

# understand how to located the nested key
# sampleDict['class'] = {'student': {'name': 'Mike', 'marks': {'physics': 70, 'history': 80}}}
# sampleDict['class']['student'] = {'name': 'Mike', 'marks': {'physics': 70, 'history': 80}}
# sampleDict['class']['student']['marks'] = {'physics': 70, 'history': 80}

# solution
print(sampleDict['class']['student']['marks']['history'])

Exercise 4: Initialize dictionary with default values

In Python, we can initialize the keys with the same values.

Given:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
0

Expected output:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
1

Show Hint

Use the

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
1 method of dict.

Show Solution

The

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
1 method returns a dictionary with the specified keys and the specified value.

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
2

Exercise 5: Create a dictionary by extracting the keys from a given dictionary

Write a Python program to create a new dictionary by extracting the mentioned keys from the below dictionary.

Given dictionary:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
3

Expected output:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
4

Show Hint

  • Iterate the mentioned keys using a loop
  • Next, check if the current key is present in the dictionary, if it is present, add it to the new dictionary

Show Solution

Solution 1: Dictionary Comprehension

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
5

Solution 2: Using the

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)
4 method and loop

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
6

Exercise 6: Delete a list of keys from a dictionary

Given:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
7

Expected output:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
8

Show Hint

  • Iterate the mentioned keys using a loop
  • Next, check if the current key is present in the dictionary, if it is present, remove it from the dictionary

To achieve the above result, we can use the dictionary comprehension or the

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
4 method of a dictionary.

Show Solution

Solution 1: Using the

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
4 method and loop

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
9

Solution 2: Dictionary Comprehension

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

res_dict = dict(zip(keys, values))
print(res_dict)
0

Exercise 7: Check if a value exists in a dictionary

We know how to check if the key exists in a dictionary. Sometimes it is required to check if the given value is present.

How do I change the key name in a nested dictionary in Python?

To change a single dictionary just reference the dictionary you want to change. And if you want to change yes entries across all the dicts you have to a loop over dict. values . Note that this won't maintain the order of the keys.

How do I change the key

Use the built-in update() method to merge the keys and values of one nested dictionary into another. Note that this method blindly overwrites values of the same key if there's a clash.

How do you rename a key in a dictionary in Python?

Change dictionary key in Python.
Add new item and then remove old one. With del statement. With pop() method..
Define a function to change the key of a dictionary. If the old key does not exist, add a new item. If the old key does not exist, do nothing..

Can you modify the keys in a dictionary Python?

Can you modify the keys of a dictionary? Yes we can modify the content of a dictionary. only values part of dictionary is modifiable.