Manual 10 - Manage Data with Dictionaries
Manual 10 - Manage Data with Dictionaries
Lab Manual 10
Important Instructions
1. Every student should have lab manual in the lab; otherwise, there will be no evaluation and
attendance.
2. The lab manual should be printed on both sides of the paper. Color printing is not required.
3. Those students who have Laptop must bring it in the lab.
4. Students should read the manual before coming to the lab.
5. Every student will have to submit assignments individually. Assignments after due date
will not be accepted.
Experiment No. 10
Manage Data with Python Dictionaries
Learning objectives
The main objective is to use a dictionary structure within your app to store data in a format that makes it easy
to look up values. By the end of this lab, you'll understand when to use a dictionary structure and how it can
help organize your data.
After you’ve completed this manual, you'll be able to:
• Identify when to use a dictionary.
• Create and modify data inside a dictionary.
• Utilize dictionary methods to access dictionary data.
Introduction
You'll frequently need to work with more complex data than strings and Boolean values. This module provides
you with tools for doing so. Let's frame the subject by considering a scenario.
Variables in Python can store various data types. Previously, you learned you can store strings and numbers:
name = 'Earth'
moons = 1
Although this method does work for smaller amounts of data, it can become increasingly complex when you're
working with related data. Imagine wanting to store information about the moons of both Earth and Jupiter.
earth_name = 'Earth'
earth_moons = 1
jupiter_name = 'Jupiter'
jupiter_moons = 79
Notice how we duplicated variables with different prefixes. This duplication can become unwieldy. Because
you'll frequently find yourself working with related sets of data, like average rainfall for different months in
different cities, storing those variables as individual values isn't a viable option. Instead, you can use Python
dictionaries.
Department of Avionics Engineering,
Institute of Space Technology, Islamabad 3|Page
Introduction to Information Technology Session: 2024 (AVE-10)
Python dictionaries allow you to work with related sets of data. A dictionary is a collection of key/value pairs.
Think of it like a group of variables inside of a container, where the key is the name of the variable, and the
value is the value stored inside it.
Create a dictionary
Python uses curly braces ({ }) and the colon (:) to denote a dictionary. You can either create an empty dictionary
and add values later or populate it at creation time. Each key/value is separated by a colon, and the name of
each key is contained in quotes as a string literal. Because the key is a string literal, you can use whatever
name is appropriate to describe the value.
Let's create a dictionary to store the name of the planet Earth, and the number of moons Earth has:
planet = {
'name': 'Earth',
'moons': 1
}
You have two keys, 'name' and 'moons'. Each key behaves in much the same way as a variable: they have a
unique name, and they store a value. However, they're contained inside of a single, larger variable,
named planet.
As with regular variables, you need to ensure that you're using the correct data types. In the moons value
of 1 in the preceding example, you didn't include quotes around the number, because you want to use an
integer. If you had used '1', Python would see this variable as a string, which would affect your ability to
perform calculations.
Unlike regular variables, key names don't need to follow standard naming rules for Python. You can use key
names to be more descriptive in your code.
print(planet.get('name'))
Output: ___________________________
As you might suspect, accessing values in a dictionary is a common operation. Fortunately, there's a shortcut.
You can also pass the key into square bracket notation ([ ]). This method uses less code than get, and most
programmers use this syntax instead. You could rewrite the preceding example by using the following:
# planet['name'] is identical to using planet.get('name')
print(planet['name'])
Although the behavior of get and the square brackets ([ ]) is generally the same for retrieving items, there's
one key difference. If a key isn't available, get returns None, and [ ] raises a KeyError.
wibble = planet.get('wibble') # Returns None
wibble = planet['wibble'] # Throws KeyError
Similar to using the square brackets ([ ]) shortcut to read values, you can use the same shortcut to modify
values. The key difference in syntax is that you use = (sometimes called the assignment operator) to provide
a new value. To rewrite the preceding example to change the name, you can use the following:
planet['name'] = 'Makemake'
# No output: name is now set to Makemake.
The key advantage to using update is the ability to modify multiple values in one operation. The next two
examples are logically the same, but the syntax is different. You're free to use whichever syntax you feel is
most appropriate. Most developers choose square brackets to update individual values.
The following example makes the same edits to our planet variable, updating the name and moons. Notice
that by using update, you're making a single call to the function, whereas using square brackets involves two
calls.
Using update:
planet.update({
'name': 'Jupiter',
'moons': 79
})
Using square brackets:
planet['name'] = 'Jupiter'
planet['moons'] = 79
Important: Key names, like everything else in Python, are case sensitive. As a result, 'name' and 'Name' are
seen as two separate keys in a Python dictionary.
To remove a key, you use pop. pop returns the value and removes the key from the dictionary. To
remove orbital period, you can use the following code:
planet.pop('orbital period')
# planet dictionary now contains: {
# name: 'jupiter'
# moons: 79
#}
To retrieve values in a nested dictionary, you chain together square brackets, or calls to get.
print(f'{planet["name"]} polar diameter: {planet["diameter (km)"]["polar"]}')
Output: _____________________________________________________________
If you were working with Earth, the output would be Earth has 1 moon(s)
Note: Use f-string formatting method.
Desired output
When you run the code you should see the following result:
Let's say you want to display the list of all rainfall. You can type out the name of each month, but that would
be tedious.
for key in rainfall.keys():
print(f'{key}: {rainfall[key]}cm')
Output:
Note: You can still use square brackets ([ ]) with a variable name, rather than the hard-coded string literal.
Determine if a key exists in a dictionary
When you update a value in a dictionary, Python will either overwrite the existing value or create a new one,
if the key doesn't exist. If you wish to add to a value rather than overwriting it, you can check to see if the key
exists by using in. For example, if you want to add a value to December or create a new one if it doesn't exist,
you can use the following:
if 'december' in rainfall:
rainfall['december'] = rainfall['december'] + 1
else:
rainfall['december'] = 1
Output: _________________________________________________________________
In this scenario, you will calculate both the total number of moons in the solar system and the average number
of moons a planet has. You will do this by using a dictionary object.
Start by creating a variable named planet_moons as a dictionary with the following key/values:
mercury: 0,
venus: 0,
earth: 1,
mars: 2,
jupiter: 79,
saturn: 82,
uranus: 27,
neptune: 14,
pluto: 5,
haumea: 2,
makemake: 1,
eris: 1
# Enter the code below
Desired output
When you run the code you should see the following result:
2. What method can you use to retrieve a value from a dictionary by using the key?
a) update
b) get
c) values
Summary
Most programs require data more complex than string and number values. In the scenario for this module,
you've been attempting to work with information about the planets in the solar system. This information
included properties such as the number of moons, and the circumference of the planets.
By using dictionaries, you were able to create a variable to store all related data. You then
used keys and values to interact with the data directly, without using key names to perform calculations.
Python dictionaries are flexible objects, allowing you to model complex and related data. In this module, you
learned how to:
• Identify when to use a dictionary.
• Create and modify data inside a dictionary.
• Use dictionary methods to access dictionary data.
Task#1
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.
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
Task#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}