Dictionaries
A dictionary stores key: value pairs, so you can look values up by name instead of by position:
capitals = {
"Zimbabwe": "Harare",
"Mauritius": "Port Louis",
"Kenya": "Nairobi",
}
print(capitals["Kenya"]) # Nairobi
capitals["Ghana"] = "Accra" # add or change an entry
print(len(capitals)) # 4
print("Mauritius" in capitals) # True: is that key there?
Asking for a key that is not there is an error (KeyError). .get is safer: it returns a default instead.
capitals.get("France", "unknown") # "unknown"
Looping
for country, city in capitals.items():
print(f"{city} is the capital of {country}")
.keys() gives just the keys and .values() just the values.
Counting with a dictionary
A very common pattern: go through items and keep a count per item.
counts = {}
for letter in "banana":
counts[letter] = counts.get(letter, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}
Your task
The starter has a prices dictionary.
price_of(item): the item's price, or0if the shop does not sell it.basket_total(items): the total price of a list of items, rounded to 2 decimal places (round(x, 2)).count_words(text): a dictionary of how many times each word appears. Words are separated by spaces (text.split()).