Dictionaries
A dictionary is a mapping between a key and value. Huh? Well let's remember lists for one bit. Every list item has an index, a number. That's essentially a mapping between a number and a value. e.g. ['hi', 'five', 'low', 'slow']
has a mapping: 0 -> 'hi', 1 -> 'five', 2 -> 'low', 3 -> 'slow'. A dictionary generalises that further, the mapping doens't have to be from a sequential integer to a value but a unique key. Dictionaries are sequences of key-value pairings. Let's have a look:
Keep the following in mind while creating dictionaries:
Use curly braces to put data inside a dictionary
Separate each key-value pairing by a comma
As with lists and tuples, use square brackets to get values from a dictionary
Exercises
A dictionary is an unordered sequence of key-value pairs. True or False?
Consider the dict that contains European football clubs and the amount of Champions League trophies they won:
clubs = {‘real madrid’: 13, ‘ac milan’: 7, ‘bayern munich’: 5, ‘ajax’: 4}
.Real Madrid are undoubtedly the greatest football team ever created but there’s space for that other Spanish team. Add Barcelona with 5 trophies.
How many trophies did ajax win? Get the value from the dictionary.
We have a function that’s interested in the teams but not so much their trophy haul. Return a list of keys for
clubs
A very ambitious but deluded Manchester City fan claims that his club has won champions league. Verify with a condition that his club has not.
Last updated