Main Page | Recent changes | Edit this page | Page history

Printable version | Disclaimers | Privacy policy

Not logged in
Log in | Help
 

Reference: Dictionaries

From 6.00 reference wiki

Strings | Lists | Dictionaries

Contents

Basics

A dictionary in Python is a collection of unordered values which are accessed by key. You can think of dictionaries as mappings from keys to values.

Dictionaries may be created directly, using curly braces:

>>> d = {'city':'Paris', 'population':2125246}

This creates the dictionary with two string keys: 'city' and 'population'. In this dictionary, the key 'city' maps to the string 'Paris' and the key 'population' maps to the integer 2125246.

>>> d['city']
'Paris'
>>> d['population']
2125246

Dictionaries are mutable, and so we may run into the same sort of aliasing complications that we discussed for lists.

Length

As with strings and lists, the len operator can be used to count the number of key-value pairs in the dictionary.

>>> len(d)
2

Equality

Two dictionaries are equal if and only if their keys are all equal, and each key refers to an equivalent element in both dictionaries:

 >>> a = {'city':'Paris', 'population':2125246}
 >>> b = {'city':'Paris', 'population':2125246}
 >>> a == b
 True
 >>> c = {'city':'Paris', 'population':2125246, 'temperature':'70F'}
 >>> a == c
 False
 >>> d = {'city':'Paris', 'population':10000000}
 >>> a == d
 False

Membership testing

We can test if a particular key is in a dictionary either by using the in operator or by using the has_key method:

 >>> d = {'city':'Paris', 'population':2125246}  
 >>> 'city' in d
 True
 >>> 'Paris' in d
 False
 >>> d.has_key('city')
 True
 >>> d.has_key('Paris')
 False

No slicing

Slicing dictionaries is not supported, since the items have no intrinsic order.

Indexing and Deleting

Retrieving values

To retrieve a value from a dictionary, we can provide a key as the index:

 >>> d = { 'apple': 'red', 'orange': 'orange', 'banana': 'yellow' }
 >>> d['apple']
 'red'
 >>> d['banana']
 'yellow'

If we provide a key not in the dictionary, we get an error:

 >>> d['Apple']   # string keys are case sensitive
 Traceback (most recent call last):
   File "<pyshell#121>", line 1, in -toplevel-
     d['Apple']
 KeyError: 'Apple'

Keys don't have to be strings:

 >>> e = { 1:'apple', 2:'orange', 5:'banana' }
 >>> e[1]
 'apple'

get(key,default)

We can also retrieve values using the get method:

 >>> d = { 'apple': 'red', 'orange': 'orange', 'banana': 'yellow' }
 >>> d.get('apple')
 'red'  

The advantage of using get is that we can pass in a default and if the key is not in the dictionary, this default value is returned, instead of an error being generated.

 >>> d.get('Apple', "I don't know")
 "I don't know"

Modifying values

We can modify the values of existing keys using an indexed assignment statement:

 >>> d = { 'apple': 'red', 'orange': 'orange', 'banana': 'yellow' }
 >>> d
 {'orange': 'orange', 'apple': 'red', 'banana': 'yellow'}
 >>> d['apple'] = 'green'   # modify a value
 >>> d
 {'orange': 'orange', 'apple': 'green', 'banana': 'yellow'}

Adding to a dictionary

We can add new key-value pairs to a dictionary by using an indexed assignment statement:

 >>> d = { 'apple': 'red', 'orange': 'orange', 'banana': 'yellow' }
 >>> d
 {'orange': 'orange', 'apple': 'red', 'banana': 'yellow'}
 >>> d['strawberry'] = 'red'    # add an assignment
 >>> d
 {'orange': 'orange', 'strawberry': 'red', 'apple': 'red', 'banana': 'yellow'}

Deleting

We can delete elements using the del operator:

 >>> d = { 'apple': 'red', 'orange': 'orange', 'banana': 'yellow' }
 >>> d
 {'orange': 'orange', 'apple': 'red', 'banana': 'yellow'}
 >>> del d['apple']    # delete an element
 >>> d
 {'orange': 'orange', 'banana': 'yellow'}

Iterating

Since the items have no intrinsic order, we have to do some extra work to iterate over the elements of a dictionary.

We can choose to iterate over the set of keys in the dictionary or the set of values.

List of keys

We can use the keys method to list a dictionary's keys and then iterate over that list:

>>> d = {'a':1,'b':2, 'cat':'Fluffers'}
>>> d.keys()
['a', 'b', 'cat']
>>> for key in d.keys():
        print key, d[key]
a 1
b 2
cat Fluffers

In general, with dictionaries we cannot predict the order keys appear in the list returned by d.keys().

List of values

We can use the values method to list a dictionary's values:

>>> d = {'a':1,'b':2, 'cat':'Fluffers'}
>>> d.values()
[1, 2, 'Fluffers']

In general, with dictionaries we cannot predict the order values appear in the list returned by d.values().

Other operations

Copying

To avoid aliasing-related bugs, e.g.

 >>> a = {'apples': 1, 'oranges': 3}
 >>> b = a
 >>> b['apples'] = 5
 >>> a
 {'apples': 5, 'oranges': 3}

You can create a copy of a dictionary:

 >>> a = {'apples': 1, 'oranges': 3}
 >>> b = a.copy()          # create a copy
 >>> b['apples'] = 5
 >>> a
 {'apples': 1, 'oranges': 3}
 >>> b
 {'apples': 5, 'oranges': 3}

Combining two Dictionaries

You can combine two dictionaries by using the update method of the primary dictionary. Note that the merge will update existing elements if they conflict.

>>> d = {'apples': 1, 'oranges': 3, 'pears': 2}
>>> ud = {'pears': 4, 'grapes': 5, 'lemons': 6}
>>> d.update(ud)
>>> d
{'grapes': 5, 'pears': 4, 'lemons': 6, 'apples': 1, 'oranges': 3}

(these notes have been adapted/expanded from the programming:python wikibook)

Retrieved from "http://slice.csail.mit.edu../../../d/i/c/Reference%7E_Dictionaries_fc71.html"

This page has been accessed 193 times. This page was last modified 02:30, 24 February 2006 by 6.00 reference wiki user Asfandyar.


[Main Page]
Main Page
Recent changes

Edit this page
Discuss this page
Page history
What links here
Related changes

Special pages
Bug reports