Beginning Python: Lists & Dictionaries
2025-10-03
Recap from last module:
=integer and float"..." or '...'True and False, used for logical comparisonsExample:
We also learned some useful tricks:
word[0]input()Today, we’ll be examining two very important data structures in Python: lists and dictionaries.
novels with multiple values?[...]novels = ["Sense and Sensibility", "Pride and Prejudice", "Mansfield Park", "Emma", "Northanger Abbey", "Persuasion", "Lady Susan"]Print list:
+ OperatorWe can also use + to concatenate lists:
[ ... ] is called the indexword[0], we access the first element of a list with the index [0]..methodvalue.methodlist.index() method to identify the indexpub_year = [1811, 1813, 1814, 1815, 1818, 1818, 1871]
susan_index = novels.index("Lady Susan")
pub_year[susan_index] # 18711818 as the index?We can also count from the end:
qmd.orwell_novels = ["Animal Farm", "Nineteen Eighty-Four", "Burmese Days", "Keep the Aspidistra Flying", "Coming Up for Air"]
pub_year = [1945, 1949, 1934, 1936, 1939].index() to find the position of Burmese Days. Use that index to print the corresponding publication year from pub_year.1936.novels: symbol:indict (dictionaries)dict is marked not with [...], but with curly braces {...}{}:To change the value of a key, you simply restate it:
dict["key"] = changed_valuekey-value Pair from the Dictionarykey-value pair:
del dict["key"]in checks to check keys (but not values)!When should use lists? Dictionaries?
ipa_segments[0] → first sound in a word.Examples:
key : value).keys) are unique, though values can repeat.Examples:
# 1. First and last novel
print(orwell_novels[0]) # Animal Farm
print(orwell_novels[-1]) # Coming Up for Air
# 2. Publication year of Burmese Days
burm_index = orwell_novels.index("Burmese Days")
print(pub_year[burm_index]) # 1934
# 3. Which novel was published in 1936?
index_1936 = pub_year.index(1936)
print(orwell_novels[index_1936]) # Keep the Aspidistra Flying# 1. Direct lookup
print(orwell_dict["Animal Farm"]) # Output: 1945
# 2. Membership check
print("Homage to Catalonia" in orwell_dict) # Output: False
# 3. Adding a new key–value pair
orwell_dict["Homage to Catalonia"] = 1937
print(orwell_dict) # Now includes: "Homage to Catalonia": 1937
# 4. Overwriting a value (fixing a mistake)
orwell_dict["Homage to Catalonia"] = 1938 # reassigns the correct year
print(orwell_dict["Homage to Catalonia"]) # Output: 1938
# 5. Delete a key–value pair
del orwell_dict["Coming Up for Air"]
print(orwell_dict) # "Coming Up for Air" has been removed