Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
IPython Notebook Essentials

You're reading from   IPython Notebook Essentials Compute scientific data and execute code interactively with NumPy and SciPy

Arrow left icon
Product type Paperback
Published in Nov 2014
Publisher
ISBN-13 9781783988341
Length 190 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Luiz Felipe Martins Luiz Felipe Martins
Author Profile Icon Luiz Felipe Martins
Luiz Felipe Martins
Arrow right icon
View More author details
Toc

Dictionaries

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:

grades['Ivan']=94

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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image