Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views5 pages

Working With Dictionaries - Lab Answersheet - Colab

The document provides a lab exercise focused on using dictionaries in Python, specifically for retrieving and assigning city data. It includes examples of creating a dictionary for Greenville, accessing its values, and manipulating a list of dictionaries representing multiple cities. The lab also introduces the use of the Pandas library to read data from an Excel file into Python dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Working With Dictionaries - Lab Answersheet - Colab

The document provides a lab exercise focused on using dictionaries in Python, specifically for retrieving and assigning city data. It includes examples of creating a dictionary for Greenville, accessing its values, and manipulating a list of dictionaries representing multiple cities. The lab also introduces the use of the Pandas library to read data from an Excel file into Python dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

2/4/25, 3:37 PM Working with Dictionaries - Lab Answersheet - Colab

keyboard_arrow_down Working with Dictionaries - Lab


Introduction
Now that we know about dictionaries in Python, it is time to practice using them. In this lesson, you'll use your knowledge of dictionaries to
retrieve and assign data about various cities.

Objectives
You will be able to:

Assign values in a dictionary


Access keys and values in a dictionary

Instructions
Here is a dictionary representing the city of Greenville, North Carolina. The area is in kilometers squared.

greenville = {'Area': 68, 'City': 'Greenville', 'Country': 'USA', 'Population': 84554}


print (greenville)

{'Area': 68, 'City': 'Greenville', 'Country': 'USA', 'Population': 84554}

Remember to press shift + enter to run the code.

Let's retrieve the population of the city and assign it to the variable greenville_population .

greenville_population = None # change None


greenville_population #84554
greenville_population = greenville['Population']
print(greenville_population)

84554

Now retrieve the area of Greenville and assign it to the variable greenville_area .

greenville_area = None
greenville_area # 68
greenville_area = greenville['Area']
print(greenville_area)

68

Now let's take a look at all of the keys in the greenville dictionary and coerce them into a list. Assign this variable to the list city_keys .

city_keys = None
city_keys # ['Area', 'City', 'Country', 'Population']
city_keys = list(greenville.keys())
print(city_keys)

['Area', 'City', 'Country', 'Population']

Alright, next let's get all of the values in our greenville dictionary and coerce it into a list. Assign that list to the variable city_values .

city_values = None
city_values # [68, 'Greenville', 'USA', 84554]
city_values =list(greenville.values())
print(city_values)

[68, 'Greenville', 'USA', 84554]

keyboard_arrow_down Working with multiple cities


We can retrieve our data from an excel or Google sheet like the one shown here named Travel Cities and Countries.

https://colab.research.google.com/drive/15VY8MWvXcE6myG_m2_LT-pZTEYQPHhNx#printMode=true 1/5
2/4/25, 3:37 PM Working with Dictionaries - Lab Answersheet - Colab

Luckily for us, we already have the spreadsheet downloaded and located in the current folder. You can find the file ( cities.xlsx ) in this
lesson's GitHub repository. Next, we will use a library called Pandas to get this data from the excel file into Python code. We already have the
code for reading an excel file into Python written for us below. Let's check it out.

Note: To import a library or module in Python, we do so by writing import followed by the name of the thing we want to import.
We can optionally include an alias for our import, which is done by writing as after the name of the thing we are importing
followed by the name we would like to use for our alias. Do not worry about aliases right now. Just know that the convention
for importing the Pandas library is to import it and alias it as pd like we see below.
We'll talk about packages and Pandas specifically in much more detail soon enough!

import pandas as pd
file_name = './cities.xlsx'

travel_df = pd.read_excel(file_name)
cities = travel_df.to_dict('records')
print(file_name)

./cities.xlsx

Remember to press shift + enter.

Great! We just used Pandas to read the data from our excel file and turn each row of data into a dictionary. Again, don't worry about exactly
how Pandas is doing this, but know that Pandas is a great tool when trying to accomplish a task such as turning data from an excel file into
data we can use in Python.

Run the cell below to see what our data looks like now.

cities

[{'City': 'Solta', 'Country': 'Croatia', 'Population ': 1700, 'Area': 59},


{'City': 'Greenville', 'Country': 'USA', 'Population ': 84554, 'Area': 68},
{'City': 'Buenos Aires',
'Country': 'Argentina',
'Population ': 13591863,
'Area': 4758},
{'City': 'Los Cabos',
'Country': 'Mexico',
'Population ': 287651,
'Area': 3750},
{'City': 'Walla Walla Valley',
'Country': 'USA',
'Population ': 32237,
'Area': 33},
{'City': 'Marakesh',
'Country': 'Morocco',
'Population ': 928850,
'Area': 200},
{'City': 'Albuquerque',
'Country': 'New Mexico',
'Population ': 559277,
'Area': 491},
{'City': 'Archipelago Sea',
'Country': 'Finland',
'Population ': 60000,
'Area': 8300},
{'City': 'Iguazu Falla',
'Country': 'Argentina',
'Population ': 0,
'Area': 672},

https://colab.research.google.com/drive/15VY8MWvXcE6myG_m2_LT-pZTEYQPHhNx#printMode=true 2/5
2/4/25, 3:37 PM Working with Dictionaries - Lab Answersheet - Colab
{'City': 'Salina Island',
'Country': 'Italy',
'Population ': 4000,
'Area': 27},
{'City': 'Toronto', 'Country': 'Canada', 'Population ': 630, 'Area': 2731571},
{'City': 'Pyeongchang',
'Country': 'South Korea',
'Population ': 2581000,
'Area': 3194}]

Now we will work with reading and manipulating this list of dictionaries, cities .

keyboard_arrow_down Working with our list of cities


First, access the third to last element and set it equal to the variable salina .

salina = None
salina
# {'Area': 27, 'City': 'Salina Island', 'Country': 'Italy', 'Population': 4000}
salina = cities[9]
print(salina)

{'City': 'Salina Island', 'Country': 'Italy', 'Population ': 4000, 'Area': 27}

Now access the fourth city in the list, and set its population equal to a variable called los_cabos_pop .

los_cabos_pop = None
los_cabos_pop # 287651
los_cabos_pop = cities[3]['Population ']
print(los_cabos_pop)

287651

Now calculate the number of cities in the list and assign the number to the variable city_count .

print(cities)

[{'City': 'Solta', 'Country': 'Croatia', 'Population ': 1700, 'Area': 59}, {'City': 'Greenville', 'Country': 'USA', 'Population ': 8

help(list)

Help on class list in module builtins:

class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.

https://colab.research.google.com/drive/15VY8MWvXcE6myG_m2_LT-pZTEYQPHhNx#printMode=true 3/5
2/4/25, 3:37 PM Working with Dictionaries - Lab Answersheet - Colab
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)

city_count = len(cities)
city_count # 12

12

Finally, change the spelling of the South Korean city, Pyeongchang, to the string 'PyeongChang' , its alternative spelling.

cities[11]['City'] = 'PyeongChang'
cities[11]['City'] # 'PyeongChang'

'PyeongChang'

import this

Now let's work on retrieving a collection of information about a dictionary. Use the appropriate dictionary method to return a list of values in
the dictionary regarding Pyeongchang. Assign the list to the variable pyeongchang_values .

help(dict)

Help on class dict in module builtins:

class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Built-in subclasses:
| StgDict
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)

https://colab.research.google.com/drive/15VY8MWvXcE6myG_m2_LT-pZTEYQPHhNx#printMode=true 4/5
2/4/25, 3:37 PM Working with Dictionaries - Lab Answersheet - Colab
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)

type(cities[11])

dict

pyeongchang_values = cities[11].values()
pyeongchang_values # ['PyeongChang', 'South Korea', 2581000, 3194]

dict_values(['PyeongChang', 'South Korea', 2581000, 3194])

And now set pyeongchang_keys equal to a list of keys in the dictionary regarding Pyeongchang.

pyeongchang_keys = cities[11].keys()
pyeongchang_keys # ['City', 'Country', 'Population', 'Area']
type(pyeongchang_keys) # list

dict_keys

Summary

In this section, we saw how to assign, retrieve, and re-assign data in a dictionary. We saw how we can retrieve a collection of information
from a dictionary, like a list of its keys and values, and we saw how we can work with a list of dictionaries.

https://colab.research.google.com/drive/15VY8MWvXcE6myG_m2_LT-pZTEYQPHhNx#printMode=true 5/5

You might also like