0% found this document useful (0 votes)
6 views

Manual 10 - Manage Data with Dictionaries

Uploaded by

Haider Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Manual 10 - Manage Data with Dictionaries

Uploaded by

Haider Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Department of Avionics Engineering

Introduction to Information Technology

Lab Manual 10

Student Name: ___________________________


Registration Number: ___________________________
Section: ___________________________
Deadline: ___________________________
Date of Submission: ___________________________

Institute of Space Technology, Islamabad


Introduction to Information Technology Session: 2024 (AVE-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.

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 2|Page
Introduction to Information Technology Session: 2024 (AVE-10)

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.

Scenario: Analyzing a solar system


Suppose you're creating a program to analyze the number of moons on different planets in the solar system.
You want to display information to the user and be able to calculate different values, like the total number of
moons in the solar system. It would be tedious to do this calculation with variables, which can only store a
string, or a number.
In this module, you'll build a program that can perform these types of operations. You'll use Python dictionaries
to model the data. By the end of the module, you'll be able to use Python dictionaries to store complex data.

Introducing Python dictionaries

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.

Read dictionary values


You can read values inside a dictionary. Dictionary objects have a get method that you can use to access a
value by using its key. If you want to print the name, you can use the following 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'])

Output: ___________ _______________

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

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 4|Page
Introduction to Information Technology Session: 2024 (AVE-10)

Modify dictionary values


You can also modify values inside a dictionary object, by using the update method. This method accepts a
dictionary as a parameter and updates any existing values with the new ones you provide. If you want to
change the name for the planet dictionary, you can use the following, for example:
planet.update({'name': 'Makemake'})
# No output: name is now set to Makemake.

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

Add and remove keys


You're not required to create all keys when you initialize a dictionary. In fact, you don't need to create any!
Whenever you want to create a new key, you assign it just as you would an existing one.
Let's say you want to update planet to include the orbital period in days:
planet['orbital period'] = 4333
# planet dictionary now contains: {
# name: 'jupiter'
# moons: 79
# orbital period: 4333
#}

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.

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 5|Page
Introduction to Information Technology Session: 2024 (AVE-10)

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
#}

Complex data types


Dictionaries can store any type of a value, including other dictionaries. This allows you to model complex
data as needed. Imagine needing to store the diameter for planet, which could be measured around its equator
or poles. You can create another dictionary inside of planet to store this information:
# Add address
planet['diameter (km)'] = {
'polar': 133709,
'equatorial': 142984
}

# planet dictionary now contains: {


# name: 'Jupiter'
# moons: 79
# diameter (km): {
# polar: 133709
# equatorial: 142984
# }
#}

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: _____________________________________________________________

Exercise: Create and modify a Python dictionary

Managing planet data


You want to create a program which will store and display information about planets. To start you will use one
planet. Create a variable named planet. Store the following values as a dictionary:
name: Mars
moons: 2

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 6|Page
Introduction to Information Technology Session: 2024 (AVE-10)
# Enter code below

Display planet data


With the variable created, you will now display information. You can retrieve information by either
using get or square brackets ([ ]) and the key name. Add the code to display the planet information in the
following format:

_____ has ______ moon(s)

If you were working with Earth, the output would be Earth has 1 moon(s)
Note: Use f-string formatting method.

# Enter code below

Add circumference information


You can update existing keys or create new ones by either using the update method or using square brackets
([ ]). When you're using update, you pass in a new dictionary object with the updated or new values. When
using square brackets, you specify the key name and assign a new value.
Add a new value to planet with a key of 'circumference (km)'. This new value should store a dictionary
with the planet's two circumferences:
polar: 6752
equatorial: 6792
Finally, add the code to print the polar circumference of the planet.
# Enter code below

Desired output
When you run the code you should see the following result:

Mars has a polar circumference of 6752

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 7|Page
Introduction to Information Technology Session: 2024 (AVE-10)

Dynamic programming with dictionaries


In your program, you want to perform various calculations, like totaling the number of moons. Additionally,
as you get into more advanced programming, you might find that you're loading this type of information from
files or a database, rather than coding directly into Python.
To help support these scenarios, Python enables you to treat both the keys and values inside of a dictionary as
a list. You can dynamically determine keys and values, and perform various calculations.
Imagine a dictionary storing monthly rainfall amounts. You would likely have keys for each month and the
associated rainfall. You want to add up the total rainfall, and writing the code to perform the operation by
using each individual key would be rather tedious.

Retrieve all keys and values


The keys() method returns a list object that contains all the keys. You can use this method to iterate through
all items in the dictionary.
Imagine you have the following dictionary, storing the last three months of rainfall.
rainfall = {
'october': 3.5,
'november': 4.2,
'december': 2.1
}

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

# Because december exists, the value will be 3.1


Department of Avionics Engineering,
Institute of Space Technology, Islamabad 8|Page
Introduction to Information Technology Session: 2024 (AVE-10)

Retrieve all values


Similar to keys(), values() returns the list of all values in a dictionary without their respective
keys. values() can be helpful when you're using the key for labeling purposes, such as the preceding example,
in which the keys are the name of the month. You can use values() to determine the total rainfall amount:
total_rainfall = 0
for value in rainfall.values():
total_rainfall = total_rainfall + value

print(f'There was {total_rainfall}cm in the last quarter.')

Output: _________________________________________________________________

Exercise - Dynamic programming with dictionaries

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

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 9|Page
Introduction to Information Technology Session: 2024 (AVE-10)

Obtain a list of moons and number of planets


Python dictionaries allow you to retrieve all the values and keys by using the values and keys methods,
respectively. Each method returns a list containing the data, which can then be used like a regular Python list.
You can determine the number of items by using len, and iterate through it by using for loops. In the dictionary
you created, the planet names are keys and the number of moons are the values.
Start by retrieving a list with the number of moons, and store this in a variable named moons. Then obtain the
total number of planets and store that value in a variable named total_planets.

# Enter code below

Determine the average number of moons


You will finish this exercise by determining the average number of moons. Start by creating a variable
named total_moons; this will be your counter for the total number of moons. Then add a for loop to loop
through the list of moons, adding each value to total_moons. Finally, calculate the average by
dividing total_moons by total_planets and displaying the value.

# Enter code below

Desired output
When you run the code you should see the following result:

Each planet has an average of 17.833333333333332 moons

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 10 | P a g e
Introduction to Information Technology Session: 2024 (AVE-10)

Check your knowledge

3. What method allows access all key names in a Python dictionary?


a) keys
b) values
c) update

2. What method can you use to retrieve a value from a dictionary by using the key?
a) update
b) get
c) values

3. What method can you use to remove a key from a dictionary?


a) values
b) [ ]
c) pop

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.

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 11 | P a g e
Introduction to Information Technology Session: 2024 (AVE-10)

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.

keys = ['Ten', 'Twenty', 'Thirty']


values = [10, 20, 30]

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}

Department of Avionics Engineering,


Institute of Space Technology, Islamabad 12 | P a g e

You might also like