Python for Java Programmers
Chapter 5: Sets and dictionaries
Dictionaries
Another powerful data structure is a dictionary. Python implements a dictionary as a built-in dict type. Dictionaries are equivalent to Hashtables or HashMaps in Java.
In case you are not familiar or have forgotten, a dictionary acts as a lookup table.
It is made up of (key, value) pairs. You use a unique key to retrieve its corresponding value.
An example use case for a dictionary would be to retrieve a student’s name given the student’s ID.

Here is an example of how you would define a dict in Python:
>>> student_dict = {"00-01-30": "Ali", "00-02-11": "Simon",
... "00-05-67": "Francesca", "00-09-88": "Cho"
... }
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca', '00-09-88': 'Cho'}
Alternatively, if you already have your data in a list of tuple pairs, you can just pass them on directly to dict().
>>> student_dict = dict([("00-01-30", "Ali"), ("00-02-11", "Simon"),
... ("00-05-67", "Francesca"), ("00-09-88", "Cho")
... ])
...
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca', '00-09-88': 'Cho'}
You can also start with an empty dictionary and add in items later.
>>> student_dict = {} # or student_dict = dict()
>>> student_dict["00-01-30"] = "Ali"
>>> student_dict["00-02-11"] = "Simon"
>>> student_dict["00-05-67"] = "Francesca"
>>> student_dict["00-09-88"] = "Cho"
>>> print(student_dict)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca', '00-09-88': 'Cho'}
As you can see above, you index an item in a dictionary using keys (and not integer sequences as in a list or tuple).
Question: What happens if you subsequently add student_dict["00-01-30"] = "Josiah"? Will Python allow this? What will happen to "Ali"? Test it out to confirm!
Dictionary keys must be unique and immutable (e.g. numbers, strings, tuples). You CANNOT for example use a list as a key (try it and see what happens!) This is quite logical - how do you expect a key to be consistent if you can modify it any time?
For the official Python interpreter version 3.6 and above, the dictionary maintains the order of the keys as you inserted them. This might not happen if you are using a different kind of Python interpreter, so it is better to treat dictionary entries as unordered!