PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python Exercises » Python Dictionary Exercise with Solutions

Python Dictionary Exercise with Solutions

Updated on: August 23, 2022 | 50 Comments

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 (:).

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
  • Exercise 2: Merge two Python dictionaries into one
  • Exercise 3: Print the value of key ‘history’ from the below dict
  • Exercise 4: Initialize dictionary with default values
  • Exercise 5: Create a dictionary by extracting the keys from a given dictionary
  • Exercise 6: Delete a list of keys from a dictionary
  • Exercise 7: Check if a value exists in a dictionary
  • Exercise 8: Rename key of a dictionary
  • Exercise 9: Get the key of a minimum value from the following dictionary
  • Exercise 10: Change value of a key in a nested dictionary

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 zip() 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 update() method

Show Solution

Solution 1: The zip() function and a dict() constructor

  • Use the zip(keys, values) to aggregate two lists.
  • Wrap the result of a zip() function into a dict() constructor.
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

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

Solution 2: Using a loop and update() 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 dict

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:

employees = ['Kelly', 'Emma']
defaults = {"designation": 'Developer', "salary": 8000}

Expected output:

{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer', 'salary': 8000}}
Show Hint

Use the fromkeys() method of dict.

Show Solution

The fromkeys() method returns a dictionary with the specified keys and the specified value.

employees = ['Kelly', 'Emma']
defaults = {"designation": 'Developer', "salary": 8000}

res = dict.fromkeys(employees, defaults)
print(res)

# Individual data
print(res["Kelly"])

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:

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"}

# Keys to extract
keys = ["name", "salary"]

Expected output:

{'name': 'Kelly', 'salary': 8000}
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

sampleDict = { 
  "name": "Kelly",
  "age":25, 
  "salary": 8000, 
  "city": "New york" }

keys = ["name", "salary"]

newDict = {k: sampleDict[k] for k in keys}
print(newDict)

Solution 2: Using the update() method and loop

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"}

# keys to extract
keys = ["name", "salary"]

# new dict
res = dict()

for k in keys:
    # add current key with its va;ue from sample_dict
    res.update({k: sample_dict[k]})
print(res)

Exercise 6: Delete a list of keys from a dictionary

Given:

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}

# Keys to remove
keys = ["name", "salary"]

Expected output:

{'city': 'New york', 'age': 25}
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 pop() method of a dictionary.

Show Solution

Solution 1: Using the pop() method and loop

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}
# Keys to remove
keys = ["name", "salary"]

for k in keys:
    sample_dict.pop(k)
print(sample_dict)

Solution 2: Dictionary Comprehension

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}
# Keys to remove
keys = ["name", "salary"]

sample_dict = {k: sample_dict[k] for k in sample_dict.keys() - keys}
print(sample_dict)

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.

Write a Python program to check if value 200 exists in the following dictionary.

Given:

sample_dict = {'a': 100, 'b': 200, 'c': 300}

Expected output:

200 present in a dict
Show Hint
  • Get all values of a dict in a list using the values() method.
  • Next, use the if condition to check if 200 is present in the given list
Show Solution
sample_dict = {'a': 100, 'b': 200, 'c': 300}
if 200 in sample_dict.values():
    print('200 present in a dict')

Exercise 8: Rename key of a dictionary

Write a program to rename a key city to a location in the following dictionary.

Given:

sample_dict = {
  "name": "Kelly",
  "age":25,
  "salary": 8000,
  "city": "New york"
}

Expected output:

{'name': 'Kelly', 'age': 25, 'salary': 8000, 'location': 'New york'}
Show Hint
  • Remove the city from a given dictionary
  • Add a new key (location) into a dictionary with the same value
Show Solution
sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}

sample_dict['location'] = sample_dict.pop('city')
print(sample_dict)

Exercise 9: Get the key of a minimum value from the following dictionary

sample_dict = {
  'Physics': 82,
  'Math': 65,
  'history': 75
}

Expected output:

Math

Show Hint

Use the built-in function min()

Show Solution
sample_dict = {
    'Physics': 82,
    'Math': 65,
    'history': 75
}
print(min(sample_dict, key=sample_dict.get))

Exercise 10: Change value of a key in a nested dictionary

Write a Python program to change Brad’s salary to 8500 in the following dictionary.

Given:

sample_dict = {
    'emp1': {'name': 'Jhon', 'salary': 7500},
    'emp2': {'name': 'Emma', 'salary': 8000},
    'emp3': {'name': 'Brad', 'salary': 500}
}

Expected output:

{
   'emp1': {'name': 'Jhon', 'salary': 7500},
   'emp2': {'name': 'Emma', 'salary': 8000},
   'emp3': {'name': 'Brad', 'salary': 8500}
}
Show Solution
sample_dict = {
    'emp1': {'name': 'Jhon', 'salary': 7500},
    'emp2': {'name': 'Emma', 'salary': 8000},
    'emp3': {'name': 'Brad', 'salary': 6500}
}

sample_dict['emp3']['salary'] = 8500
print(sample_dict)

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

 Python Exercises

  • Python Exercises Home
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com