Book Image

IPython Notebook Essentials

By : Luiz Felipe Martins
Book Image

IPython Notebook Essentials

By: Luiz Felipe Martins

Overview of this book

Table of Contents (15 chapters)
IPython Notebook Essentials
About the Author
About the Reviewers


Python dictionaries are a data structure that contains key-item pairs. The keys must be immutable types, usually strings or tuples. Here is an example that shows how to construct a dictionary:

grades = {'Pete':87, 'Annie':92, 'Jodi':78}

To access an item, we provide the key as an index as follows:

print grades['Annie']

Dictionaries are mutable, so we can change the item values using them. If Jodi does extra work to improve her grade, we can change it as follows:

grades['Jodi'] += 10
print grades['Jodi']

To add an entry to a dictionary, just assign a value to a new key:


However, attempting to access a nonexistent key yields an error.

An important point to realize is that dictionaries are not ordered. The following code is a standard idiom to iterate over a dictionary:

for key, item in grades.iteritems():
    print "{:s}'s grade in the test is {:d}".format(key, item)

The main point here is that the output is not at all related to the order in which the entries were added to the dictionary.

For more details on the dictionary interface, you can refer to