Python dictionaries, often called hash tables in other languages, are extremely powerful and surprisingly easy to use. They work just like a normal word dictionary works: looking up a key (word) in the dictionary gives back the information (definition) for that key (word).
If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!
To define a dictionary, we use curly brackets {}
. Inside the curly brackets, we define key: value
pairs, like so:
>>> word_dictionary = {'Aardvark': 'An animal with a long nose or something.',
... 'Apple': 'A red fruit (or sometimes green (or sometimes yellow)).',
... 'Brontosaurus': 'A big vegan dinosaur with a long neck and tail.'}
The keys can be any hashable type (which mostly includes strings and integers), and the value can be anything: string, int, object, class, function, list, your Aunt Sue, even another dictionary!
Using the dictionary is easy as well. To get the value associated to a key, we use a similar format as getting a value from a list.
>>> word_dictionary['Apple']
"A red fruit (or sometimes green (or sometimes yellow))."
And to add a new key-value pair to the dictionary, we again use a similar pattern to the list:
>>> word_dictionary['Twerk'] = "Some dance kids do now-adays? I guess?"
>>> print(word_dictionary['Twerk'])
Some dance kids do now-adays? I guess?
Changing something works the same way as adding:
>>> word_dictionary['Twerk'] = "Some stupid dance kids do now-adays."
To remove a key-value pair from the dictionary, use the pop
function:
>>> word_dictionary.pop('Twerk')
'Some stupid dance kids do now-adays.'
>>> word_dictionary.keys()
dict_keys(['Apple', 'Aardvark', 'Brontosaurus'])
There are two things to note here: 1) The keys
method of a dictionary returns a set-like object (which, for our purposes, works very similarly to a list) that shows you all the keys of the dictionary and 2) Twerk does not belong in the dictionary.
You can also use the for loop with a dictionary. The simplest and most common way to iterate over a dictionary gives you the keys of the dictionary, which we try here! (sorted
is a built-in function that sorts alphabetically whatever you pass into it.)
>>> for word in sorted(word_dictionary):
... print("key: " + word)
... print("value: " + word_dictionary[word])
...
key: Aardvark
value: An animal with a long nose or something.
key: Apple
value: A red fruit (or sometimes green (or sometimes yellow)).
key: Brontosaurus
value: A big vegan dinosaur with a long neck and tail.