Dictionaries are another type of Python container. Instead of storing values by index, they store them associated with a key.
You create dictionaries using curly brackets, assiging values to their keys using a colon, e.g.
a = { "cat" : "mieow", "dog" : "woof", "horse" : "neigh" }
a = { "cat" : "mieow", "dog" : "woof", "horse" : "neigh"}
a
You can look up values in the dictionary by placing the key in square brackets. For example, we can look up the value associated with the key "cat" using a["cat"]
.
a["cat"]
What happens if the key does not exist?
a['fish']
You insert items into the dictionary by assigning values to keys, e.g.
a["fish"] = "bubble"
a
You can list all of the keys or values of a dictionary using the keys
or values
functions (which you can find using tab completion and Python help)
help(a.values)
a.keys()
a.values()
You can loop over the dictionary by looping over the keys and looking up the values in a for loop, e.g.
for key in a.keys():
print("A %s goes %s" % (key, a[key]))
You can put anything as a value into a dictionary, including other dictionaries and even lists. The keys should be either numbers or strings.
b = { "a" : ["aardvark", "anteater", "antelope"], "b" : ["badger", "beetle"], 26.5: a}
What do you think is at b["a"][-1]
? What about b[26.5]["fish"]
?
b[26.5]["fish"]
Below you have a dictionary that contains the full mapping of every letter to its Morse-code equivalent.
letter_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.',
'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--',
'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
'0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
' ':'/' }