HyperLearning AI - Introduction to Python

An introductory course to the Python 3 programming language, with a curriculum aligned to the Certified Associate in Python Programming (PCAP) examination syllabus (PCAP-31-02).
https://knowledgebase.hyperlearning.ai/courses/introduction-to-python

05. Data Aggregates Part 2

https://knowledgebase.hyperlearning.ai/courses/introduction-to-python/modules/5/data-aggregates-part-2

In this module we will introduce additional common collection data structures available in Python and associated methods, including:

  • Tuples - constructing, accessing and manipulating tuple data collection structures
  • Dictionaries - constructing, accessing and manipulating dictionary data collection structures

1. Tuples

1.1. Defining a Tuple

In [18]:
# Create an empty tuple
empty_tuple = ()
print(empty_tuple)

# Create a tuple with only 1 element by using a trailing comma
tuple_one_element_1 = 'elem1', 
print(tuple_one_element_1)
tuple_one_element_2 = 10, 
print(tuple_one_element_2)
tuple_one_element_3 = ('a', )
print(tuple_one_element_3)

# If we forget the trailing comma, then Python will recognise it as a string
print(type(tuple_one_element_1))
tuple_one_element_4 = ('a')
print(type(tuple_one_element_4))

# Create a tuple with 5 elements
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
()
('elem1',)
(10,)
('a',)
<class 'tuple'>
<class 'str'>
(1, 2, 3, 4, 5)
In [10]:
# Initialise a tuple with a list
my_tuple_from_a_list = tuple(["a", "b", "c"])
my_tuple_from_a_list
Out[10]:
('a', 'b', 'c')

1.2. Standard for Heterogeneity

In [7]:
# Create a heterogeneous tuple containing information about an individual
individual_tuple = ("Barack", "Obama", 59)
print(individual_tuple)
('Barack', 'Obama', 59)
5

1.4. Index and Negative Indexing

In [13]:
# Access elements in a tuple by their index numbers
my_tuple = ("Barack", "Obama", "04/08/1961", 59, "Male", 1.85, "American")
print(my_tuple[0])
print(my_tuple[3])
print(my_tuple[-1])
print(my_tuple[-2])
Barack
59
American
1.85

1.5. Slice Notation

In [14]:
# Use slice notation on tuples
print(my_tuple[:])
print(my_tuple[2:])
print(my_tuple[:4])
print(my_tuple[2:5])
print(my_tuple[1::2])
('Barack', 'Obama', '04/08/1961', 59, 'Male', 1.85, 'American')
('04/08/1961', 59, 'Male', 1.85, 'American')
('Barack', 'Obama', '04/08/1961', 59)
('04/08/1961', 59, 'Male')
('Obama', 59, 1.85)

1.6. Tuple Length

In [15]:
# Using the len() function on tuples
print(len(my_tuple))
7

1.7. Tuple Membership

In [16]:
# Test whether an element exists in a tuple
if 'Obama' in my_tuple:
    print(f"This tuple correponds to information about Barack Obama")
else:
    print(f"This tuple does not correspond to information about Barack Obama")
This tuple correponds to information about Barack Obama

1.8. Deleting Tuples

In [17]:
# Delete a tuple
print(my_tuple_from_a_list)
del my_tuple_from_a_list
print(my_tuple_from_a_list)
('a', 'b', 'c')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-7299abfd2c7f> in <module>
      1 print(my_tuple_from_a_list)
      2 del my_tuple_from_a_list
----> 3 print(my_tuple_from_a_list)

NameError: name 'my_tuple_from_a_list' is not defined

1.9. Joining Tuples

In [19]:
# Join two tuples to create a new tuple
my_first_tuple = ('a', 1, 'b', 2, 'c', 3)
my_second_tuple = ('d', 4, 'e', 5, 'f', 6)
my_third_tuple = my_first_tuple + my_second_tuple
print(my_third_tuple)
('a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6)

1.10. Tuple Assignment

In [22]:
# Use tuple packing to pack values into a single tuple
barack_obama = "Barack", "Obama", 59
print(barack_obama)
print(type(barack_obama))
('Barack', 'Obama', 59)
<class 'tuple'>
In [23]:
# Use sequence unpacking to assign values to variables from a given sequence
barack_obama_first_name, barack_obama_last_name, barack_obama_age = barack_obama
print(barack_obama_first_name)
print(barack_obama_last_name)
print(barack_obama_age)
Barack
Obama
59
In [24]:
# Swap values assigned to two different variables
a = 10
b = 99
print(a)
print(b)
(a, b) = (b, a)
print(a)
print(b)
10
99
99
10

1.11. Tuple Methods

In [27]:
# Create a tuple
my_tuple = (0, 1, 0, 1, 1, 0, 0, 1, 1, 1)

# tuple.count(x)
print(my_tuple.count(0))
print(my_tuple.count(1))
print(my_tuple.count(2))

# tuple.index(x)
print(my_tuple.index(0))
print(my_tuple.index(1))
print(my_tuple.index(2))
4
6
0
0
1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-ae8e4eb7a1fc> in <module>
     10 print(my_tuple.index(0))
     11 print(my_tuple.index(1))
---> 12 print(my_tuple.index(2))

ValueError: tuple.index(x): x not in tuple

1.12. Iterating Tuples

In [28]:
# Create a tuple
my_diatomic_tuple = (0, 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)

# Iterate the tuple using a while loop
i = 0
while i < len(my_diatomic_tuple):
    print(f'Diatomic Sequence - Element #{i + 1}: {my_diatomic_tuple[i]}')
    i += 1

# Iterate the tuple using a for loop with the range function
for x in range(len(my_diatomic_tuple)):
    print(f'Diatomic Sequence - Element #{x + 1}: {my_diatomic_tuple[x]}')

# Iterate the tuple using a for loop with the in operator
for elem in my_diatomic_tuple:
    print(elem)

# Iterate the tuple using a for loop with the in operator and enumerate function
for idx, elem in enumerate(my_diatomic_tuple):
    print(f'Diatomic Sequence - Element #{idx + 1}: {elem}')
Diatomic Sequence - Element #1: 0
Diatomic Sequence - Element #2: 1
Diatomic Sequence - Element #3: 1
Diatomic Sequence - Element #4: 2
Diatomic Sequence - Element #5: 1
Diatomic Sequence - Element #6: 3
Diatomic Sequence - Element #7: 2
Diatomic Sequence - Element #8: 3
Diatomic Sequence - Element #9: 1
Diatomic Sequence - Element #10: 4
Diatomic Sequence - Element #11: 3
Diatomic Sequence - Element #12: 5
Diatomic Sequence - Element #13: 2
Diatomic Sequence - Element #14: 5
Diatomic Sequence - Element #15: 3
Diatomic Sequence - Element #16: 4
Diatomic Sequence - Element #1: 0
Diatomic Sequence - Element #2: 1
Diatomic Sequence - Element #3: 1
Diatomic Sequence - Element #4: 2
Diatomic Sequence - Element #5: 1
Diatomic Sequence - Element #6: 3
Diatomic Sequence - Element #7: 2
Diatomic Sequence - Element #8: 3
Diatomic Sequence - Element #9: 1
Diatomic Sequence - Element #10: 4
Diatomic Sequence - Element #11: 3
Diatomic Sequence - Element #12: 5
Diatomic Sequence - Element #13: 2
Diatomic Sequence - Element #14: 5
Diatomic Sequence - Element #15: 3
Diatomic Sequence - Element #16: 4
0
1
1
2
1
3
2
3
1
4
3
5
2
5
3
4
Diatomic Sequence - Element #1: 0
Diatomic Sequence - Element #2: 1
Diatomic Sequence - Element #3: 1
Diatomic Sequence - Element #4: 2
Diatomic Sequence - Element #5: 1
Diatomic Sequence - Element #6: 3
Diatomic Sequence - Element #7: 2
Diatomic Sequence - Element #8: 3
Diatomic Sequence - Element #9: 1
Diatomic Sequence - Element #10: 4
Diatomic Sequence - Element #11: 3
Diatomic Sequence - Element #12: 5
Diatomic Sequence - Element #13: 2
Diatomic Sequence - Element #14: 5
Diatomic Sequence - Element #15: 3
Diatomic Sequence - Element #16: 4

1.13. Tuples as Return Values

In [32]:
import math

# Return both the circumference and area of a circle given a radius
def circle(radius):
    """ Return the (circumference, area) of a circle given its radius """
    circumference = 2 * math.pi * radius
    area = math.pi * radius * radius
    return (circumference, area)

my_radius = 10
my_cirumference, my_area = circle(my_radius)
print(f'The circumference of a circle of radius {my_radius}cm is {my_cirumference}cm')
print(f'The area of a circle of radius {my_radius}cm is {my_area}cm\u00b2')
The circumference of a circle of radius 10cm is 62.83185307179586cm
The area of a circle of radius 10cm is 314.1592653589793cm²

1.14. Tuples in Lists

In [37]:
# Create a list of tuples
my_list_of_tuples = [(1, 'abc'), (2, 'def'), (3, 'ghi')]
print(my_list_of_tuples)
print(my_list_of_tuples[0])
print(my_list_of_tuples[0][0])
print(my_list_of_tuples[1])
print(my_list_of_tuples[1][1])
print(my_list_of_tuples[2])
print(my_list_of_tuples[2][0])
print(type(my_list_of_tuples))
[(1, 'abc'), (2, 'def'), (3, 'ghi')]
(1, 'abc')
1
(2, 'def')
def
(3, 'ghi')
3
<class 'list'>

1.15. Lists in Tuples

In [38]:
# Create a tuple of lists
my_tuple_of_lists = ([1, 2, 3], ['abc', 'def', 'ghi'])
print(my_tuple_of_lists)
print(my_tuple_of_lists[0])
print(my_tuple_of_lists[0][0])
print(my_tuple_of_lists[1])
print(my_tuple_of_lists[1][1])
print(type(my_tuple_of_lists))
([1, 2, 3], ['abc', 'def', 'ghi'])
[1, 2, 3]
1
['abc', 'def', 'ghi']
def
<class 'tuple'>

1.16. Multi-Dimensional Tuples

In [40]:
# Create an immutable 3 x 3 identity matrix
identity_matrix = ((1, 0, 0), (0, 1, 0), (0, 0, 1))
for row in identity_matrix:
    for elem in row:
        print(elem, end=' ')
    print()
1 0 0 
0 1 0 
0 0 1 

2. Dictionaries

2.1. Defining a Dictionary

In [1]:
# Create an empty dictionary
my_empty_dict = {}
print(my_empty_dict)

# Create a dictionary mapping countries (keys) to their population size in millions (value)
country_population_dict = {
    "China": 1394,
    "India": 1326,
    "Japan": 126,
    "United Kingdom": 66,
    "United States": 330
}
print(country_population_dict)
{}
{'China': 1394, 'India': 1326, 'Japan': 126, 'United Kingdom': 66, 'United States': 330}
In [2]:
# Create a dictionary using the dict() function and a list of tuples
country_population_dict = dict([
    ("China", 1394), 
    ("India", 1326), 
    ("Japan", 126), 
    ("United Kingdom", 66), 
    ("United States", 330)
])
print(country_population_dict)
{'China': 1394, 'India': 1326, 'Japan': 126, 'United Kingdom': 66, 'United States': 330}

2.2. Accessing Dictionary Items

In [4]:
# Access a dictionary value item by its key using square brackets
japan_population_m = country_population_dict["Japan"]
print(f'The population of Japan is {japan_population_m}m')

# Access a dictionary value item by its key using the get() method
print(f'The population of China is {country_population_dict.get("China")}m')
The population of Japan is 126m
The population of China is 1394m
In [7]:
# Perform a lookup using a non-existent key using square brackets
brazil_population_m = country_population_dict["Brazil"]
print(f'The population of Brazil is {brazil_population_m}m')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-7-72eca4a7a180> in <module>
      1 # Perform a lookup using a non-existent key using square brackets
----> 2 brazil_population_m = country_population_dict["Brazil"]
      3 print(f'The population of Brazil is {brazil_population_m}m')

KeyError: 'Brazil'
In [8]:
# Perform a lookup using a non-existent key using the get() method
print(f'The population of Brazil is {country_population_dict.get("Brazil")}m')
The population of Brazil is Nonem

2.3. Modifying Dictionary Items

In [9]:
# Create a dictionary of GDP rankings by country
gdp_rankings_dict = {
    "China": 2,
    "India": 8,
    "Japan": 3,
    "United Kingdom": 5,
    "United States": 1
}
print(gdp_rankings_dict)

# Modify the ranking of an existing country
gdp_rankings_dict["India"] = 7
print(gdp_rankings_dict)
{'China': 2, 'India': 8, 'Japan': 3, 'United Kingdom': 5, 'United States': 1}
{'China': 2, 'India': 7, 'Japan': 3, 'United Kingdom': 5, 'United States': 1}

2.4. Adding Dictionary Items

In [11]:
# Add a country to the population dictionary
print(country_population_dict)
country_population_dict["South Korea"] = 52
print(country_population_dict)
{'China': 1394, 'India': 1326, 'Japan': 126, 'United Kingdom': 66, 'United States': 330, 'South Korea': 'Seoul'}
{'China': 1394, 'India': 1326, 'Japan': 126, 'United Kingdom': 66, 'United States': 330, 'South Korea': 52}

2.5. Removing Dictionary Items

In [12]:
# Remove a key:value pair from the country population dictionary usign the del keyword
print(country_population_dict)
del country_population_dict["Japan"]
print(country_population_dict)
{'China': 1394, 'India': 1326, 'Japan': 126, 'United Kingdom': 66, 'United States': 330, 'South Korea': 52}
{'China': 1394, 'India': 1326, 'United Kingdom': 66, 'United States': 330, 'South Korea': 52}
In [13]:
# Remove a key:value pair from the country population dictionary usign the pop() method
country_population_dict.pop("United Kingdom")
print(country_population_dict)

# Remove the last inserted key:value pair using the popitem() method
country_population_dict.popitem()
print(country_population_dict)
{'China': 1394, 'India': 1326, 'United States': 330, 'South Korea': 52}
{'China': 1394, 'India': 1326, 'United States': 330}
In [14]:
# Delete the GDP rankings dictionary
print(gdp_rankings_dict)
del gdp_rankings_dict
print(gdp_rankings_dict)
{'China': 2, 'India': 7, 'Japan': 3, 'United Kingdom': 5, 'United States': 1}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-14-393aa71f1bc3> in <module>
      2 print(gdp_rankings_dict)
      3 del gdp_rankings_dict
----> 4 print(gdp_rankings_dict)

NameError: name 'gdp_rankings_dict' is not defined

2.6. Iterating Dictionaries

In [15]:
# Use a for loop to iterate through the keys in a given dictionary, printing the keys
for key in country_population_dict:
    print(key)
print()
    
# Use a for loop to iterate through the keys in a given dictionary, printing the values
for key in country_population_dict:
    print(country_population_dict[key])
China
India
United States

1394
1326
330
In [17]:
# Use the values() method to iterate over the values of a dictionary
for v in country_population_dict.values():
    print(v)
print()

# Use the items() method to iterate over both keys and values of a dictionary
for k, v in country_population_dict.items():
    print(f'The population of {k} is {v}m')
1394
1326
330

The population of China is 1394m
The population of India is 1326m
The population of United States is 330m

2.7. Checking Key Existence

In [19]:
# Test for the existence of a key in a given dictionary
if "South Korea" in country_population_dict:
    print(f'The population of South Korea is {country_population_dict["South Korea"]}m')
else:
    print('South Korea does not exist in our dictionary of populations.')
South Korea does not exist in our dictionary of populations.

2.8. Dictionary Comprehension

In [20]:
# Create a dictionary of keys (1 - 10) and values (key squared) using dictionary comprehension
squares_dict = {num: num*num for num in range(1, 11)}
print(squares_dict)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
In [30]:
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
    "Mercury": 91_691_000, 
    "Venus": 41_400_000, 
    "Mars": 78_340_000, 
    "Jupiter": 628_730_000, 
    "Saturn": 1_275_000_000, 
    "Uranus": 2_723_950_000, 
    "Neptune": 4_351_400_000
}
print(f'Distance between the Earth and the other planets in the Solar System (km):\n{earth_planets_distance_km_dict}\n')

# Convert to AU using dictionary comprehension
km_to_au = 149_600_000
earth_planets_distance_au_dict = { planet: round((km / km_to_au), 2) for (planet, km) in earth_planets_distance_km_dict.items() }
print(f'Distance between the Earth and the other planets in the Solar System (AU):\n{earth_planets_distance_au_dict}')
Distance between the Earth and the other planets in the Solar System (KM):
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 4351400000}

Distance between the Earth and the other planets in the Solar System (AU):
{'Mercury': 0.61, 'Venus': 0.28, 'Mars': 0.52, 'Jupiter': 4.2, 'Saturn': 8.52, 'Uranus': 18.21, 'Neptune': 29.09}
In [33]:
# Create a dictionary of planets within 100km of the Earth
planetary_neighbour_limit_km = 100_000_000
earth_closest_planets_dict = { k:v for (k, v) in earth_planets_distance_km_dict.items() if v < planetary_neighbour_limit_km }
print(f'Distance between the Earth and our closest planets in the Solar System (km):\n{earth_closest_planets_dict}')
Distance between the Earth and our closest planets in the Solar System (KM):
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000}

In [34]:
# Create a dictionary of average planetary distances from the Earth, using km for the inner planets and AU for the outer planets
km_to_au = 149_600_000
inner_planet_limit_km = 100_000_000
earth_planets_km_au_dict = { k: ( v if v < inner_planet_limit_km else round((v / km_to_au), 2) ) for (k, v) in earth_planets_distance_km_dict.items() }
print(f'Distance between the Earth and the other planets in the Solar System (km for inner planets and AU for outer planets):\n{earth_planets_km_au_dict}')
Distance between the Earth and the other planets in the Solar System (km for inner planets and AU for outer planets):
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 4.2, 'Saturn': 8.52, 'Uranus': 18.21, 'Neptune': 29.09}

2.9. Filtering Dictionaries

In [38]:
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
    "Mercury": 91_691_000, 
    "Venus": 41_400_000, 
    "Mars": 78_340_000, 
    "Jupiter": 628_730_000, 
    "Saturn": 1_275_000_000, 
    "Uranus": 2_723_950_000, 
    "Neptune": 4_351_400_000
}

# Filter to keep only the inner planets
inner_planets = ["Mercury", "Venus", "Earth", "Mars"]
earth_inner_planets_distance_km_dict = { key: earth_planets_distance_km_dict[key] for key in set(inner_planets).intersection(earth_planets_distance_km_dict.keys()) }
print(earth_inner_planets_distance_km_dict)
{'Venus': 41400000, 'Mercury': 91691000, 'Mars': 78340000}

2.10. Copying Dictionaries

In [41]:
# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
    "Mercury": 91_691_000, 
    "Venus": 41_400_000, 
    "Mars": 78_340_000, 
    "Jupiter": 628_730_000, 
    "Saturn": 1_275_000_000, 
    "Uranus": 2_723_950_000, 
    "Neptune": 4_351_400_000
}
print(earth_planets_distance_km_dict)

# Create a shallow copy of this dictionary
shallow_copy_dict = earth_planets_distance_km_dict
shallow_copy_dict["Earth"] = 0

# Modify the original dictionary and observe changes to the shallow copy
earth_planets_distance_km_dict["Neptune"] = 29.09
print(earth_planets_distance_km_dict)
print(shallow_copy_dict)
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 4351400000}
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 29.09, 'Earth': 0}
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 29.09, 'Earth': 0}
In [42]:
import copy

# Create a dictionary of average distance (in km) of planets from the Earth
earth_planets_distance_km_dict = {
    "Mercury": 91_691_000, 
    "Venus": 41_400_000, 
    "Mars": 78_340_000, 
    "Jupiter": 628_730_000, 
    "Saturn": 1_275_000_000, 
    "Uranus": 2_723_950_000, 
    "Neptune": 4_351_400_000
}
print(earth_planets_distance_km_dict)

# Create a deep copy of this dictionary
deep_copy_dict = copy.deepcopy(earth_planets_distance_km_dict)
deep_copy_dict["Earth"] = 0

# Modify the original dictionary and observe no changes to the deep copy
earth_planets_distance_km_dict["Neptune"] = 29.09
print(earth_planets_distance_km_dict)
print(deep_copy_dict)
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 4351400000}
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 29.09}
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Neptune': 4351400000, 'Earth': 0}

2.11. Nested Dictionaries

In [47]:
import pprint

# Create a nested dictionary
nested_multiplication_table_2d_dict = {
    1: {
        1:1, 2:2, 3:3, 4:4, 5:5
    }, 
    2: {
        1:2, 2:4, 3:6, 4:8, 5:10
    }, 
    3: {
        1:3, 2:6, 3:9, 4:12, 5:15
    }, 
    4: {
        1:4, 2:8, 3:12, 4:16, 5:20
    }, 
    5: {
        1:5, 2:10, 3:15, 4:20, 5:25
    }
}
pprint.pprint(nested_multiplication_table_2d_dict)
{1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5},
 2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10},
 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20},
 5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25}}
In [48]:
# Create the same nested dictionary using dictionary comprehension
nested_multiplication_table_2d_dict = { key1: {key2: key1 * key2 for key2 in range(1, 6)} for key1 in range(1, 6) }
pprint.pprint(nested_multiplication_table_2d_dict)
{1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5},
 2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10},
 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20},
 5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25}}

2.12. Dictionaries from Tuples

In [49]:
# Create a list of tuples containing countries and their size in km^2
country_area_tuples = [("Russia", 17_098_242), ("Canada", 9_984_670), ("United States", 9_857_348), ("China", 9_596_961)]
print(country_area_tuples)

# Convert this list of tuples to an equivalent dictionary
country_area_dict = { key[0]: key[1] for key in country_area_tuples}
pprint.pprint(country_area_dict)
[('Russia', 17098242), ('Canada', 9984670), ('United States', 9857348), ('China', 9596961)]
{'Canada': 9984670,
 'China': 9596961,
 'Russia': 17098242,
 'United States': 9857348}

2.13. Sparse Matrix

In [51]:
# Create a sparse matrix with a dictionary of tuple keys
sparse_matrix_dict = {(0, 1): 1, (2, 2): 2, (4, 1): 3}
print(f'The value of the element at row 0 and column 1 is {sparse_matrix_dict.get((0, 1), 0)}')
print(f'The value of the element at row 0 and column 3 is {sparse_matrix_dict.get((0, 3), 0)}')
print(f'The value of the element at row 2 and column 1 is {sparse_matrix_dict.get((2, 1), 0)}')
print(f'The value of the element at row 2 and column 2 is {sparse_matrix_dict.get((2, 2), 0)}')
print(f'The value of the element at row 4 and column 1 is {sparse_matrix_dict.get((4, 1), 0)}')
The value of the element at row 0 and column 1 is 1
The value of the element at row 0 and column 3 is 0
The value of the element at row 2 and column 1 is 0
The value of the element at row 2 and column 2 is 2
The value of the element at row 4 and column 1 is 3

2.14. Common Dictionary Methods

In [71]:
import pprint

# Create a dictionary
earth_planets_distance_km_dict = {
    "Mercury": 91_691_000, 
    "Venus": 41_400_000, 
    "Mars": 78_340_000, 
    "Jupiter": 628_730_000, 
    "Saturn": 1_275_000_000, 
    "Uranus": 2_723_950_000, 
    "Neptune": 4_351_400_000
}
pprint.pprint(earth_planets_distance_km_dict)
print()

# dict.clear()
nested_multiplication_table_2d_dict = { key1: {key2: key1 * key2 for key2 in range(1, 6)} for key1 in range(1, 6) }
pprint.pprint(nested_multiplication_table_2d_dict)
nested_multiplication_table_2d_dict.clear()
pprint.pprint(nested_multiplication_table_2d_dict)
print()

# dict.copy()
copy_dict = earth_planets_distance_km_dict.copy()
pprint.pprint(copy_dict)
print()

# dict.fromkeys(keys, value)
keys = [2, 3, 5, 7, 11]
prime_dict = dict.fromkeys(keys)
pprint.pprint(prime_dict)

v = "prime"
labelled_prime_dict = dict.fromkeys(keys, v)
pprint.pprint(labelled_prime_dict)
print()

# dict.get(key, default)
print(earth_planets_distance_km_dict.get("Venus"))
print(earth_planets_distance_km_dict.get("Earth"))
print(earth_planets_distance_km_dict.get("Earth", 0))
print()

# dict.items()
print(earth_planets_distance_km_dict.items())
print()

# dict.keys()
print(earth_planets_distance_km_dict.keys())
print()

# dict.pop(key, default)
print(earth_planets_distance_km_dict.pop("Neptune"))
print(earth_planets_distance_km_dict.pop("Earth", 0))
print()

# dict.popitem()
earth_planets_distance_km_dict["Earth"] = 0
print(earth_planets_distance_km_dict)
earth_planets_distance_km_dict.popitem()
print(earth_planets_distance_km_dict)
print()

# dict.setdefault(key, value)
pluto_average_distance_km = earth_planets_distance_km_dict.setdefault("Pluto", 4_970_600_000)
print(pluto_average_distance_km)
print(earth_planets_distance_km_dict)
print()

# dict.update(iterable)
dict_updates = {"Sun": 151_460_000, "Asteroid Belt": 390_400_000}
earth_planets_distance_km_dict.update(dict_updates)
pprint.pprint(earth_planets_distance_km_dict)
print()

# dict.values()
print(earth_planets_distance_km_dict.values())
{'Jupiter': 628730000,
 'Mars': 78340000,
 'Mercury': 91691000,
 'Neptune': 4351400000,
 'Saturn': 1275000000,
 'Uranus': 2723950000,
 'Venus': 41400000}

{1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5},
 2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10},
 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20},
 5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25}}
{}

{'Jupiter': 628730000,
 'Mars': 78340000,
 'Mercury': 91691000,
 'Neptune': 4351400000,
 'Saturn': 1275000000,
 'Uranus': 2723950000,
 'Venus': 41400000}

{2: None, 3: None, 5: None, 7: None, 11: None}
{2: 'prime', 3: 'prime', 5: 'prime', 7: 'prime', 11: 'prime'}

41400000
None
0

dict_items([('Mercury', 91691000), ('Venus', 41400000), ('Mars', 78340000), ('Jupiter', 628730000), ('Saturn', 1275000000), ('Uranus', 2723950000), ('Neptune', 4351400000)])

dict_keys(['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'])

4351400000
0

{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Earth': 0}
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000}

4970600000
{'Mercury': 91691000, 'Venus': 41400000, 'Mars': 78340000, 'Jupiter': 628730000, 'Saturn': 1275000000, 'Uranus': 2723950000, 'Pluto': 4970600000}

{'Asteroid Belt': 390400000,
 'Jupiter': 628730000,
 'Mars': 78340000,
 'Mercury': 91691000,
 'Pluto': 4970600000,
 'Saturn': 1275000000,
 'Sun': 151460000,
 'Uranus': 2723950000,
 'Venus': 41400000}

dict_values([91691000, 41400000, 78340000, 628730000, 1275000000, 2723950000, 4970600000, 151460000, 390400000])

2.15. Common Dictionary Functions

In [72]:
# len()
pprint.pprint(earth_planets_distance_km_dict)
print(len(earth_planets_distance_km_dict))
{'Asteroid Belt': 390400000,
 'Jupiter': 628730000,
 'Mars': 78340000,
 'Mercury': 91691000,
 'Pluto': 4970600000,
 'Saturn': 1275000000,
 'Sun': 151460000,
 'Uranus': 2723950000,
 'Venus': 41400000}
9