Dictionaries
Python also offers a dictionary type. This is based on a hash table, and the lookup time is almost constant, irrespective of size. Dictionaries are enclosed in braces ({ }), and the keys and values are displayed separated by a colon. You can access and set their elements with a notation similar to list indexes:
>>> fur_colors = {}
>>> fur_colors['Tinky-Winky'] = 'purple'
>>> fur_colors['Dipsy'] = 'green'
>>> fur_colors['LaLa'] = 'yellow'
>>> fur_colors
{'Tinky-Winky': 'purple', 'Dipsy': 'green', 'LaLa': 'yellow'}
>>> fur_colors['LaLa']
'yellow'
>>>Dictionaries have no natural order. They support some useful methods of searching, e.g., by keys, values, and whether or not a certain key is present:
>>> fur_colors.keys()
['Tinky-Winky', 'Dipsy', 'LaLa']
>>> fur_colors.values()
['purple', 'green', 'yellow']
>>> fur_colors.items() # converts to a list of tuples
[('Tinky-Winky', 'purple'), ('Dipsy', 'green'), ('LaLa', 'yellow')]
>>> len(fur_colors)
3
>>> fur_colors.has_key('Po')
0
>>>Lists and dictionaries together allow you to build more powerful data structures, such as sets or even database indexes, in few lines of code. The values in a dictionary can be anything, while the keys can be strings, numbers, or tuples of other values. In Chapter 6, we show how to construct some extremely useful utilities from dictionaries.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access