Contents
These are the exercises for the article Python Dictionaries for Beginners: A Complete Lesson With Exercises
1. When should you prefer a dictionary over a list? What advantages does it have?
2. Given the following elements and their symbols, create a dictionary that allows you to look up the symbol given the element name as a key. Assume the element name and symbol names have the cases as shown. Name the dictionary “elements”.
Hydrogen H
Bismuth Bi
Iron Fe
Carbon C
Silicon Si
Helium He
3. Write a for loop that loops over the elements dictionary you created in exercise 2, above. Print each item as “Symbol => Name” on a single line,
4. Assuming the elements dictionary is in scope (declared globally for example, or you can add it to the function), write a function that takes an element name and returns the symbol name. If the element name is not found, return the string “NOT FOUND”.
def find_symbol(element: str):
"""Todo: Replace None with your code"""
None
5. Add the following elements and their symbols to the elements table.
Oxygen O
Sodium Na
Zinc Zn
6. The elements table allows you to look up symbols, given an element name. How could you create a dictionary that would allow you to look up the element name, given a symbol name?
7. You have a list of sensor IDs and sensor readings, as given in the next cell (the sensor ID comes first in each pair). Also shown is the code for iterating through the list. Write the code to create a dictionary that maps each unique sensor ID to a list of readings related to it, as shown in the following psuedocode: {sensor_id: [reading1, reading2, ...], ...}
Name the dictionary “readings”.
reading_list = [("id001", 93.9), ("id001", 93.9), ("id007", 33.5), ("id001", 22.0), ("id003", 55.1), ("id007", 22.10)]
for reading in reading_list:
print(f"id = {reading[0]}, reading = {reading[1]}")
# Your code to create the readings dictionary here:
id = id001, reading = 93.9
id = id001, reading = 93.9
id = id007, reading = 33.5
id = id001, reading = 22.0
id = id003, reading = 55.1
id = id007, reading = 22.1
8. Write the code to create a dictionary named “squares”. Each key should be a number between one and ten, and each value should be the square of the number.
10. What is wrong with the following code? You can run it if you need to in order to refresh your memory about this topic:
grades = {[99, 95]: "Kalea", [85, 100]: "Antoine"}
grades