Dictionaries

Dictionaries are tables that can find stuff very quickly because each key is associated with a value. It is really like using the index of a book to jump immediately to the content you need. Keys and values can belong to different data types. The only prerequisite for keys is that they should be hashable (that's a fairly complex concept; simply keep the keys as simple as possible and, therefore, don't try to use a dictionary or a list as a key). To create a dictionary, you can use curly brackets, as follows:

b_dict = {1: 1, '2': '2', 3.0: 3.0}

The following are some handy methods that you can remember while working with dictionaries:

  • To access the value indexed by the k key, use the [] notation, as follows:
b_dict['2'] # prints ...

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.