Python Dictionary Values: Mixed Types, Lists and Totals
Dictionary values can hold different types. Read individual values by key, or use values() to work with them together.
Read Dictionaries and Lists first. This lesson shows how to inspect dictionary values and choose which ones you can total.
Run each example on its own with the Run button. Each block supplies its own fixed data and needs no imports or helper functions.
Read mixed values
A dictionary can store text, numbers and booleans together. Each lookup returns the stored value with its original type.
player = {"name": "Alice", "score": 38, "done": False}
print(player["name"])
print(player["done"])
This prints Alice, then False.
Store lists and missing results
A value can also be a list or None. Use None here to mean that no best score has been selected yet.
player = {"scores": [3, 5], "best": None}
print(player["scores"])
print(player["best"])
print("best" in player)
This prints [3, 5], None, then True. A stored None is different from a missing key. Your program decides what None means.
Count entries and total numbers
len() counts key-value pairs. values() supplies the stored values; sum() adds them when they are numbers.
banked = {"Alice": 30, "Bob": 55}
print(sum(banked.values()))
print(len(banked))
This prints 85, then 2. Use a dictionary of numeric scores for a total. Calling sum() on the mixed player values above would raise TypeError because they include text or a list.
An empty dictionary
An empty dictionary has no entries. Summing its values gives 0.
banked = {}
print(sum(banked.values()))
print(len(banked))
Both lines print 0. These examples use fixed data; they do not check or convert values read from a file.
See also: Nested data.
Your turn
Print the player's list of scores. Then print the total banked amount and the number of banked entries.
player = {"name": "Cara", "scores": [4, 6], "best": None}
banked = {"Alice": 12, "Bob": 8, "Cara": 10}
# add three prints: the scores list, the banked total, and the entry count
Expected output
[4, 6]
30
3