Functions and Dictionaries
Functions and dictionaries go well together. A function can take a dictionary as an argument and use the values it needs:
def describe(pet):
return f"{pet['name']} is a {pet['species']}."
rex = {"name": "Rex", "species": "dog", "age": 3}
print(describe(rex))
print(describe({"name": "Kiwi", "species": "parrot", "age": 4}))Rex is a dog.
Kiwi is a parrot.The parameter pet is a name for whatever dictionary you pass in the call: in the first call it's Rex's dictionary, in the second one Kiwi's. Instead of separate arguments for the name and the species, you pass one dictionary, and the function takes what it needs from it.
A function can also take a list of dictionaries. This one returns the dictionary of the oldest pet. It uses the pattern for the largest value from the lesson on loops:
def oldest(pets):
result = pets[0]
for pet in pets:
if pet["age"] > result["age"]:
result = pet
return result
pets = [
{"name": "Rex", "species": "dog", "age": 3},
{"name": "Bella", "species": "cat", "age": 5},
{"name": "Kiwi", "species": "parrot", "age": 4}
]
winner = oldest(pets)
print(winner["name"], "is the oldest.")Bella is the oldest.And a function can return a new dictionary. That's handy when you create many dictionaries of the same shape: you write the keys only once, in the function, and every dictionary it returns has the same keys:
def create_pet(name, species):
return {"name": name, "species": species, "age": 0}
new_pets = []
new_pets.append(create_pet("Coco", "rabbit"))
new_pets.append(create_pet("Max", "dog"))
print(new_pets)[{'name': 'Coco', 'species': 'rabbit', 'age': 0}, {'name': 'Max', 'species': 'dog', 'age': 0}]"name": name may look strange. On the left of the colon is the key, the text "name" in quotes. On the right is its value: the parameter name, which holds "Coco" in the first call. A new pet is always 0 years old, so "age" is 0 in every dictionary the function creates.
A typical mistake is to forget return. The function then gives back None, and the list would be [None, None].
Instructions
Complete the function total_score(): it should add up the scores of all the players in the list it gets and return the sum. The program should then print Total: 355.
Complete the function create_player(): it should return a new player, a dictionary with the key "name" holding the parameter name, and the key "score" holding 0. The last two lines should then be {'name': 'Max', 'score': 0} and {'name': 'Lily', 'score': 0}.
Start programming for free
8/9