Dictionaries
Dictionaries are an associative data structure: given a key they return a certain value. Unlike lists, dictionary entries are not ordered. Python does not restrict the values of a dictionary, but keys need to be immutable.
We can define a dictionary by using a list of key-value pairs separated by a colon and enclosed by a curly bracket. For example:
dicc = {1: ‘uno’, 2: ‘dos’, 3: ‘tres’}
defines a dictionary called dicc
that associates a number with the
name of the number in Spanish.
Values are accessed just as lists elements, but instead of the index, we use the key.
dicc[2]
We can use this notation to create new or alter existing dictionary entries.
dicc[4] = 'cuatro'adds to the dictionary and
dicc[2] = 'dois'changes the entry for key
2
falsely to the Portuguese value.
To test for membership of a key in a dictionary, we use the keyword in
,
which is also used to iterate through all of the keys in a dictionary in a for-loop.
Dictionaries are very valuable tools in writing good, readable code, as you will discover over the years of programming in Python. We barely scratch the surface in this module and course.