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

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'] = 120
{'zinc': 30, 'gold': 79, 'vibranium': 1000, 'radium': 88}

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.

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

# your solution here
for element, atomic_number in atomic_numbers.items():
    ...
{'zinc': 30, 'gold': 79, 'vibranium': 1000, 'radium': 88}

Exercise 5: Rewrite this code using a dictionary#

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

for index in range(len(mouse_names)):
    print('The weight of', mouse_names[index] ,'is', mouse_weights[index], 'grams.')
The weight of Jerry is 32 grams.
The weight of Minnie is 29 grams.
The weight of Pinky is 25 grams.
The weight of Brain is 38 grams.
The weight of Mickey is 30 grams.
# your solution here
fat_mice = {'Jerry': 32, 'Minnie': 29,}

print(fat_mice)
for mouse, weight in fat_mice.items():
    print('The weight of', mouse ,'is', weight, 'grams.')
{'Jerry': 32, 'Minnie': 29}
The weight of Jerry is 32 grams.
The weight of Minnie is 29 grams.