Composite data types#

Exercise 1#

We are given data as a tuple. We want to set the third value to 3. Fix below code to make this work:

data = (1, 2, -12, 4)
data[2] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[1], line 2
      1 data = (1, 2, -12, 4)
----> 2 data[2] = 3

TypeError: 'tuple' object does not support item assignment
# fix the code here

Exercise 2: Make a digital phone book using a dictionary#

Make a phone book using a dictionary, so we can easily look up phone numbers using the name as the key. We are given two lists of matching names and phone numbers. Generate a phone book dictionary that has each name as a key and the associated phone number as a value.

names = ['Alice', 'Yolanda', 'Tom', 'Francoise', 'Alan']
phone_numbers = [432246234, 190998010, 984703, 123156, 9630]

# your solution here\
phone_book = {}

for idx in range(len(names)):
    phone_book[names[idx]] = phone_numbers[idx]

phone_book
{'Alice': 432246234,
 'Yolanda': 190998010,
 'Tom': 984703,
 'Francoise': 123156,
 'Alan': 9630}

Exercise 3: Modifying dictionaries#

We are given a dictionary with the name of chemical elements and the associated atomic number (number of protons in the nucleus).

  1. Delete vibranium from the list dictionary.

  2. Add the element silver and it’s atomic number to the dictionary

Print the dictionary to check your results

atomic_numbers = {'zinc': 30, 'gold': 79, 'vibranium': 1000, 'radium': 88}
print(atomic_numbers)

# your solution here
del atomic_numbers['vibranium']
atomic_numbers['silver'] = 108

atomic_numbers
{'zinc': 30, 'gold': 79, 'vibranium': 1000, 'radium': 88}
{'zinc': 30, 'gold': 79, 'radium': 88, 'silver': 108}

Exercise 4: For loops and dictionaries#

Now use a for loop to loop over the key:value pairs of the modified dictionary and print the element name and it’s atomic number in a nicely formatted way (“The atomic number for ELEMENT_NAME is ATOMIC_NUMBER.”), each element in a separate line.

num = 1/3
print(f'The number is {num:1.2f}.')
The number is 0.33.

Exercise 5: Rewrite this code using a dictionary#

mouse_names = ['Jerry', 'Minnie', 'Pinky', 'Brain', 'Mickey']
mouse_weights = [32, 29, 25, 38, 30]

mw = {}

for idx in range(len(mouse_names)):
    mw[mouse_names[idx]] = mouse_weights[idx]
mw
{'Jerry': 32, 'Minnie': 29, 'Pinky': 25, 'Brain': 38, 'Mickey': 30}
# your solution here
for name, weight in mw.items():
    print(name, weight)
Jerry 32
Minnie 29
Pinky 25
Brain 38
Mickey 30