PySchools Python Quick Reference Guide

Dictionaries

«  Strings   ::   Contents   ::   Tuples  »

Dictionaries

Python Dictionary is a container type for storing data in key/value pairs. The data is enclosed within the curly braces {}. It is similar to associative array in php and hashtable and hashmap in Java. A dictionary can be created in the following ways:

>>> a = {'a':'apple', 'b':'boy', 'c':'cat'}             # creating a dictionary with values assigned
>>> a                                                   # printing its content
{'a': 'apple', 'b': 'boy', 'c': 'cat'}
>>> type(a)                                             # getting its data type
<type 'dict'>

>>> b = dict()                                          # create empty dictionary
>>> b['john'] = 10                                      # add a new key/value pair to the dictionary
>>> b['mary'] = 20                                      # add another key/value pair to the dictionary
>>> b
{'john': 10, 'mary': 20}
>>> b['john'] = 30                                      # change the value of existing key: 'john'
>>> b
{'john': 30, 'mary': 20}
>>> c = [('a', 1), ('b', 2), ('c', 3)]
>>> dict(c)                                             # create a dictionary from a list of tuples.
{'a':1, 'b':2, 'c':3}

Accessing Values in Dictionaries

There are a few built-in methods for accessing all the keys, values or individual elements in a dictionary.

>>> x = {'a':'apple', 'b':'boy', 'c':'cat'}
>>> x['a']                                          # getting the value for the key: 'a'
'apple'
>>> x.get('a')                                      # another way of getting the value for the key: 'a'
>>> x.has_key('a')                                  # Check whether the key: 'a' exists
True
>>> x['d']                                          # key not found, produces error
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
KeyError: 'd'

>>> x.keys()                                        # get all the keys in the dictionary
['a', 'c', 'b']
>>> x.values()                                      # get all the values in the dictionary
['apple', 'cat', 'boy']
>>> x.items()                                       # get all the key/value pairs in the dictionary
[('a', 'apple'), ('c', 'cat'), ('b', 'boy')]

Deleting Dictionaries and/or their Contents

See examples below on how to remove one element or all the elements in a dictionary.

>>> x = {'a':'apple', 'b':'boy', 'c':'cat'}
>>> del x['a']                                      # delete the element with key: 'a'
>>> x
{'b': 'boy', 'c': 'cat'}
>>> x.clear()                                       # empty the dictionary
>>> x
{}
>>> del x                                           # delete the dictionary
>>> x                                               # dictionary no longer exists, produces error
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'x' is not defined

Summary of dictionary operations

Each example in the table below assumes a dictionary ‘s’.

>>> s = {'a':1, 'b':2, 'c':3}
Operation Explanation Example Result on s
s.keys() return a list of keys of ‘s’ s.keys() [‘a’, ‘b’, ‘c’]
s.values() return a list of values of ‘s’ s.values() [1, 2, 3]
s.items() return key-value pairs of ‘s’ s.items() [(‘a’, 1), (‘b’, 2), (‘c’, 3)]
s.get(k [, x]) s[k] if k in ‘s’ else x s.get(‘e’, 5) 5 (no change in ‘s’)
s.setdefault(k [, x]) s[k] if k in ‘s’, else x (also setting it) s.setdefault({‘e’, 5}) 5 (‘s’ contains {“e”:5})
s.update([b]) update ‘s’ with key-value pairs from ‘b’, return None s.update({‘d’:4}) {‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4}
del s[k] remove s[k] from ‘s’ del s[‘b’] {‘a’:1, ‘c’:3}
s.pop(k [, x]) s[k] if k in ‘s’, else x (and remove s[k]) s.pop(‘c’, 5) {‘a’:1, ‘b’:2}

See also

Ready for some practice? Test your understanding at PySchools: Dictionaries.

«  Strings   ::   Contents   ::   Tuples  »