Back to articles list Articles
12 minutes read

Top 10 Python Dictionary Exercises for Beginners

Have you ever wondered how Python manages to organize and manipulate data efficiently? Python dictionaries play a pivotal role.

In this article, we'll take you on an exciting journey through Python dictionaries, offering a curated list of exercises with solutions to help you grasp the concept and unlock the full potential of dictionaries.

Understanding Python Dictionaries

Before diving into the exercises, let's take a moment to understand Python dictionaries and how to use them.

In Python, a dictionary is an unordered collection of key-value pairs. It allows you to store and retrieve data using keys, which can be of various data types (including strings and numbers). Dictionaries are enclosed in curly braces {} and contain key-value pairs separated by colons. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

In this dictionary, 'name', 'age', and 'city' are keys, and 'John', 30, and 'New York' are their corresponding values. Dictionaries are flexible and dynamic, making them valuable in various programming scenarios.

To complement your learning journey, I recommend checking out our courses Python Basics, Part 2 and Python Data Structures. The exercises presented in this article are drawn from these courses. They’re designed to help you grasp Python's fundamentals and explore data structures comprehensively. Our interactive courses offer an engaging learning experience, ensuring you understand the concepts and apply them effectively in real-world programming tasks.

About These Python Dictionary Exercises

To provide some Python dictionary examples, we've curated a set of Python dictionary exercises suitable for beginners. Each exercise includes the problem statement, a Python solution, and a detailed discussion on how the solution works.

Now, here's a question for you: Are you ready to unlock the potential of Python dictionaries and level up your programming skills? Let's embark on a journey to master these data structures!

Pro Tip: Spend 20 minutes on each exercise, then check the solutions for maximum learning!

First, let’s look at some exercises from our Python Data Structures course.

1.  Modifying Elements in a Python Dictionary

Directions

Jessica plays a game in which she serves restaurant customers – e.g., she plays a waitress. You are given a dictionary with:

  • The names of customers sitting in the restaurant right now (the keys).
  • The waiting time in minutes, i.e. how long ago the customer came into the restaurant (the first value in the tuple).
  • Status, i.e. if a given person is still waiting for food ('still waiting'), has gotten their food ('got the food :)'), or has left after waiting too long ('left without eating :('). This is the second value in the tuple. The last case ('left without eating :(') happens when the customer waits for food for 20+ minutes.

Update the status of those customers who have waited for their food for 20 minutes or more (and their status is not 'got the food :)'). Also, count how many customers have left.

Print the following information:

{} customers left.

Starter Code

restaurant_customers = { 
  'John Steven': (10, 'still waiting'),
  'Jane Black': (5, 'still waiting'),
  'Mark Dawson': (15, 'got the food :)'),
  'Janet Roberts': (30, 'left without eating :('),
  'John Parker': (22, 'still waiting'),
  'Anne Edwards': (18, 'got the food :)'),
  'Mary Rogers': (7, 'got the food :)'),
  'Emma Reed': (35, 'got the food :)'),
  'Sophia Steven': (25, 'still waiting'),
  'Amelia Cook': (32, 'still waiting'),
  'John Scott': (15, 'still waiting'),
  'George Famous': (20, 'still waiting'),
  'Jack Baker': (38, 'got the food :)')
} 

Code Solution

restaurant_customers = { 
  'John Steven': (10, 'still waiting'),
  'Jane Black': (5, 'still waiting'),
  'Mark Dawson': (15, 'got the food :)'),
  'Janet Roberts': (30, 'left without eating :('),
  'John Parker': (22, 'still waiting'),
  'Anne Edwards': (18, 'got the food :)'),
  'Mary Rogers': (7, 'got the food :)'),
  'Emma Reed': (35, 'got the food :)'),
  'Sophia Steven': (25, 'still waiting'),
  'Amelia Cook': (32, 'still waiting'),
  'John Scott': (15, 'still waiting'),
  'George Famous': (20, 'still waiting'),
  'Jack Baker': (38, 'got the food :)')
}

counter = 0
for customer in restaurant_customers:
  time, status = restaurant_customers[customer]
  if time >= 20 and status != 'got the food :)':
    status = 'left without eating :('
  if status == 'left without eating :(':
    counter += 1
    restaurant_customers[customer] = (time, status)
    print(counter, 'customers left.')

Code Explanation

First, we loop through the restaurant_customers dictionary and check if the time is greater than or equal to 20 and if the status is not "got the food :)". If it is, we change the status to "left without eating :(".

Next, we keep a counter of how many customers left without eating.

Finally, we print the counter to return the number of customers left.

2.  The Python get() Function 

Directions

Simplify the template code so that it uses the get() function.

Starter Code

employees = [
('Maria', 'Polish'), ('Jean', 'French'),
('Juan', 'Spanish'), ('Dima', 'Ukrainian'),
('Agata', 'Polish'), ('Rafal', 'Polish'),
('Diego', 'Spanish'), ('Stan', 'Ukrainian')
]

dict_results = {}
for employee in employees:
  _, nationality = employee
if nationality not in dict_results:
  dict_results[nationality] = 0
  dict_results[nationality] += 1

Code Solution

employees = [
('Maria', 'Polish'), ('Jean', 'French'),
('Juan', 'Spanish'), ('Dima', 'Ukrainian'),
('Agata', 'Polish'), ('Rafal', 'Polish'),
('Diego', 'Spanish'), ('Stan', 'Ukrainian')
]

dict_results = {}
for employee in employees:
  _, nationality = employee
  dict_results[nationality] = dict_results.get(nationality, 0) + 1

print(dict_results)

Code Explanation

First, we create an empty dictionary called dict_results, and then we iterate through the employees dictionary.

Each employee is represented by a tuple with 2 elements: the first element is the name, and the second one is the nationality. We use the get() function to append the number of nationals for a given nationality.

After printing, we get the following output:

{'Polish': 3, 'French': 1, 'Spanish': 2, 'Ukrainian': 2}

3.  Grouping with Python Dictionaries

Directions

You are given a list of tuples storing information about airports. Each tuple consists of the airport's name and its number of runways.

Your task is to create a dictionary named runways, which will group all airport names by the number of runways. In other words, the keys should represent the numbers of runways, and the values should store lists of airport names.

Starter Code

airport_runways = [
('Warsaw', 2),
('Vienna', 2),
('Frankfurt', 4),
('London Heathrow', 2),
('Fukuoka', 1),
('Madrid', 4)
]

Code Solution

airport_runways = [
('Warsaw', 2),
('Vienna', 2),
('Frankfurt', 4),
('London Heathrow', 2),
('Fukuoka', 1),
('Madrid', 4)
]

runways = {}
for airport in airport_runways:
  airport_name, runway = airport
if runway not in runways:
  runways[runway] = []
  runways[runway].append(airport_name)

Code Explanation

The airport_runways variable is a list of tuples. Each tuple contains the name of an airport and its number of runways.

To make a dictionary containing the number of runways and the airports with that many runways, we create an empty dictionary called runways.

Next, we loop through each airport in the airport_runways list and assign the tuple’s first element to a variable called airport_name and its second element to a variable called runway.

If the runway number is not in the runways dictionary, we add it as a key and set its value to an empty list.

Finally, we add the airport name to the list, which is the value for that key.

4.  Linking Python Dictionaries

Directions

You are given a dictionary with salaries for 2017. Create a copy of this dictionary and name it salaries_2018. In 2018, everyone got a 10% raise. Update the 2018 dictionary to reflect the raise; each value in salaries_2018 should be an integer.

Finally, print both dictionaries and observe that the values in the dictionary salaries_2017 were not modified. This confirms that salaries_2018 is a separate dictionary.

Starter Code

salaries_2017 = {'Anna': 4000, 'Mark': 5000, 'Jane': 5500, 'John': 3000}

Code Solution

salaries_2017 = {'Anna': 4000, 'Mark': 5000, 'Jane': 5500, 'John': 3000}
salaries_2018 = salaries_2017.copy()
for key in salaries_2018.keys():
  salaries_2018[key] = int(salaries_2018[key] * 1.1)
  print(salaries_2017)
  print(salaries_2018)

Code Explanation

First, we create a dictionary salaries_2017 with four key-value pairs.

Next, we copy the dictionary salaries_2017 into the new dictionary salaries_2018.

Then we iterate through the keys of the dictionary salaries_2018; we change the value of salaries_2018[key] for each key by multiplying it by 1.1.

Finally, we print out the dictionaries salaries_2017 and salaries_2018 after each iteration.

5.  The Python update() Function

Directions

You are given a dictionary with salaries for 2019. Use the salaries_update dictionary to update salaries for 2019. Print the modified salaries_2019 dictionary.

Note that a new employee, Mary, has been added to salaries_2019.

Starter Code

salaries_2019 = {'Anna': 5000, 'Mark': 5000, 'Jane': 6500, 'John': 3500}
salaries_update = {'Anna': 5500, 'Mary': 4000}

Code Solution

salaries_2019 = {'Anna': 5000, 'Mark': 5000, 'Jane': 6500, 'John': 3500}
salaries_update = {'Anna': 5500, 'Mary': 4000}
salaries_2019.update(salaries_update)
print(salaries_2019)

Code Explanation

First, we create two dictionaries: salaries_2019 and salaries_update.

Next, we update the salaries_2019 dictionary with the salaries_update dictionary using the update() function.

Finally, we print the updated salaries_2019 dictionary.

6.  Using get() with Python Grouping

Directions

Rewrite the template code so that it uses the get() function.

Starter Code

airport_runways = [
('Warsaw', 2),
('Vienna', 2),
('Frankfurt', 4),
('London Heathrow', 2),
('Fukuoka', 1),
('Madrid', 4)
]

runways = {}
for airport in airport_runways:
  airport_name, runway = airport
if runway not in runways:
  runways[runway] = []
  runways[runway].append(airport_name)

Code Solution

airport_runways = [
('Warsaw', 2),
('Vienna', 2),
('Frankfurt', 4),
('London Heathrow', 2),
('Fukuoka', 1),
('Madrid', 4)
]

runways = {}
for airport in airport_runways:
  airport_name, runway = airport
  runways[runway] = runways.get(runway, []) + [airport_name]

Code Explanation

First, we create a dictionary called runways. Then, we loop through the airport_runways list.

For each airport, we create a tuple with the airport name and runway number. Finally, we append the airport name to the list of airports with the same runway number.

If you found the exercises above helpful, you can find many more in our Python Data Structure course.

Next, let’s look at some exercises from our Python Basics, Part 2 course.

7.  Deleting Python Dictionary Elements

Directions

Delete the dictionary item from 2001.

Starter Code

os_releases = {
2015: 'Windows 10',
2013: 'Windows 8.1',
2012: 'Windows 8',
2009: 'Windows 7',
2007: 'Windows Vista'
}

os_releases[2001] = 'Windows XP'

Code Solution

os_releases = {2015: 'Windows 10', 2013: 'Windows 8.1', 2012: 'Windows 8', 2009: 'Windows 7', 2007: 'Windows Vista'}

os_releases[2001] = 'Windows XP'

del os_releases[2001]

Code Explanation

First, we create a dictionary called os_releases with the year of each Windows release as keys and the Windows name as values.

Next, we add the release year and name of Windows XP to the dictionary.

Finally, we use del to remove the release year and name of Windows XP from the dictionary.

8.  The Python in Operator

Directions

Ask the user to provide an integer. Use the prompt “Enter a year between 2000 and 2018 to check if there was a major Windows release”.

 

If there is an item for the given year in os_releases, print:

A major version found: {os_release}. 

Otherwise, print:

No major version found.

Starter Code

os_releases = {
2015: 'Windows 10',
2013: 'Windows 8.1',
2012: 'Windows 8',
2009: 'Windows 7',
2007: 'Windows Vista',
2001: 'Windows XP'
}

user_key = int(input('Enter a year between 2000 and 2018 to check if there was a major Windows release. '))

Code Solution

os_releases = {
2015: 'Windows 10',
2013: 'Windows 8.1',
2012: 'Windows 8',
2009: 'Windows 7',
2007: 'Windows Vista',
2001: 'Windows XP'
}

user_key = int(input('Enter a year between 2000 and 2018 to check if there was a major Windows release. '))

if user_key in os_releases:
  print('A major version found:', os_releases[user_key])
else:
  print('No major version found')

Code Explanation

When the user keys in a year, we check that the value matches an OS release. If it does, it will print it. Otherwise, it will print 'No major version found'.

8. Iterating Over Python Dictionaries Using items()

Directions

Windows 1.0 was the first major operating system released by Microsoft (in 1985). For each system version in the dictionary, print the following sentence:

{version_name} was released in {year} - {x} years after Windows 1.0.

Starter Code

os_releases = {
2015: 'Windows 10',
2013: 'Windows 8.1',
2012: 'Windows 8',
2009: 'Windows 7',
2007: 'Windows Vista',
2001: 'Windows XP'}

Code Solution

os_releases = {2015: 'Windows 10', 2013: 'Windows 8.1', 2012: 'Windows 8', 2009: 'Windows 7', 2007: 'Windows Vista', 2001: 'Windows XP'}

for key, value in os_releases.items():
  print(value, 'was released in', key, '-', (key-1985), 'years after   Windows 1.0')

Code Explanation

We have a dictionary called os_releases that maps the year of a Windows OS release to the name of that operating system.

First, we loop through the keys and values in the dictionary and print them out. Note that we have used the items() function to iterate over all the key-value pairs in the dictionary os_releases. The items() method returns a list of tuples. Each tuple contains a key and its value from the dictionary.

Finally, we print out the values of the tuples.

9.  Python Dictionaries as Function Arguments

Directions

Write a function named max_value() that takes a dictionary and returns its greatest value. Assume that all values in the dictionary are natural numbers.

Hint

Create a temporary variable in the function with an initial value of 0.

Code Solution

def max_value(dictionary):
  max = 0
  for value in dictionary.values():
    if value > max:
      max = value
  return max

Code Explanation

First, we create a function called max_value that takes a dictionary as input and returns the maximum value in the dictionary.

We set a counter called max to 0.

Next, we iterate through the values in the dictionary. If the current value is greater than the maximum value, we update the maximum value.

Finally, the output is the maximum value after iterating through the dictionary.

10.  Returning Python Dictionaries from Functions

Directions

Modify the function add_ten so that it returns a new dictionary instead of modifying the dictionary passed in as an argument.

Starter Code

def add_ten(dictionary):
  for key in dictionary.keys():
    if dictionary[key] % 2 == 0:
      dictionary[key] += 10

Code Solution

def add_ten(dictionary):
  new_dict = dictionary.copy()
  for key in dictionary.keys():
    if dictionary[key] % 2 == 0:
      new_dict[key] += 10
  return new_dict

Code Explanation

We have a function named add_ten that takes a dictionary as a parameter. The function adds 10 to every value in dictionary and returns new_dict.

We create a new dictionary inside the function called new_dict that contains all the values of my_dictionary. Next, we loop through each key in dictionary.

If the value associated with a key is even, we add 10 to the value and store the result back in the dictionary with the same key.

Finally, we return new_dict at the end of the function.

Want More Python Dictionary Exercises?

We hope you have enjoyed the Python dictionary exercises in this article. I encourage you to explore our three-course Python Basics learning track and the Python Data Structures in Practice course for a more comprehensive understanding of Python. Feel free to check our articles on sorting and filtering dictionaries with Python for more learning.

Lastly, do not hesitate to visit LearnPython.com to keep learning about Python.