6. Dictionaries#
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.
A empty dictionary can be created using the dict function.
D = dict()
or just by using {}
D = {}
key value pairs can be added to dictionary using [].
D["esdger"] = "dijksta"
D["ada"] = "lovelace"
A value can be found in a dictionary using the key
D["ada"]
'lovelace'
and the value can be changed.
D["ada"] = "Byron"
print(D)
{'esdger': 'dijksta', 'ada': 'Byron'}
6.1. Exercise 1#
Do dictionary keys have to be of the same type ?
6.2. Solution 1#
6.3. Exercise 2#
Do dictionary values have to be of the same type ?
6.4. Solution 2#
6.5. Exercise 3#
Do dictionary values have to be unique ?
6.6. Solution 2#
6.7. Exercise 4#
What types can be used as keys in a dictionary ? Experiment and find out.
Dictionaries can be created with content using {:}
DD = {1 : 3,"a" : (1,True)}
print(DD)
{1: 3, 'a': (1, True)}
The in operator can be used to find if a value is in sequence, be it a list, tuple, or dictionary.
L = [1,2,3]
2 in L
True
T = (1,"hello",True)
False in T
False
In a dictionary, in operates on the keys, not the values.
D = {"a" : 1,(2,3) : True}
(2,3) in D
True
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search algorithm. As the list gets longer, the search time gets longer in direct proportion to the size of the list. For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a dictionary.
6.8. Exercise 5#
Install the numpy library using pip.
6.9. Solution 5#
6.10. Exercise 6#
import the numpy library. Use help to find out about the poisson function in the random module of numpy. Note - the numpy library is discussed in more detail in a seperate chapter.
6.11. Solition 6#
6.12. Exercise 7#
Generate a sample of size 100 from a poisson distribution with \(\lambda = 2\).
6.13. Solution 7#
6.14. Exercise 8#
Write a function that uses a dictionary to “bin” a sample of size \(n\) drawn from a poisson distribution with rate \(\lambda\).
6.15. Solution 8#
6.16. Exercise 9#
Spend 5 minutes thinking of as many use cases for dictionary as you can.
For each use case explain why you would use a dictionary and not a list.
How would you describe a dictionary “mathematically” ? How does this description differ (if at all) from a “mathematical” description of a list ?