OUTDATED, DO NOT USE: This tutorial was written in 1999 and was based on Python 1.5.2, which today is a really old version. I would not recommend using this tutorial to learn modern Python as the language has changed significantly. This page is left here in it's mostly-original form for historic reference only. Please consult the Python website for current documentation.

Dictionaries

Dictionaries are another built-in type which give Python a lot of power. In other high-level languages, they may be called associative arrays or mappings.

  • Dictionaries are containers of arbitrary values which are uniquely indexed by some other value (like a name-value pair). They are written like
    mydict = { 'Bob' : 'vanilla', 'Karen' : 'strawberry',
               'Henry' : 'chocolate', 'Frank' : 'vanilla' }
    
    and are referenced similar to arrays
    print "Karen's favorite flavor is %s" % mydict['Karen']
    
  • Any reasonable type can be used as the key: strings, numbers, etc. Anything may be used as the value part: strings, lists, tuples, even other dictionaries.
  • A key can only appear once in a dictionary. But the values associated with the keys may repeat (such as 'vanilla' above).
  • The elements in a dictionary are not sorted. Any order you give will not be preserved. This is because they are implemented as hash tables inside of Python.
    D = { 'one':1, 'two':2, 'three':3 }
    print D   --> {'one':1, 'three':3, 'two':2}
    
  • Since dictionaries are not ordered sequences, most operations which apply to sequences can not be used with dictionaries. This includes slicing, appending, and iterating with a for loop.
  • Elements can be updated or new elements inserted by assiging a value to a dictionary index,
    D['four'] = 4
    print D   --> {'one':1, 'two':2, 'three':3, 'four':4}
    
    D['two'] = 222
    print D   --> {'one':1, 'two':222, 'three':3, 'four':4}
    
  • Elements can be removed by using the del statement.
    del D['two']
    print D   --> {'one':1, 'three':3, 'four':4}
    

Dictionary operations

  • You can test if a dictionary has a given key with
    if mydict.has_key( 'five' ):
       print 'It is %s' % mydict['five']
    
  • You can get a list of all the keys in the dictionary with
    print mydict.keys()  --> ['one','three','four']
    
  • You can get a list of all the values (without keys) with
    print mydict.values()  --> [1,3,4]
    
  • You can convert the whole dictionary to a list (which you can then use in a for loop). Each element of the list will be a tuple of length 2, where the key is [0] and the value is [1].
    print mydict.items()  --> [('one',1), ('three',3), ('four',4)]
    
  • Finally, you can empty out a dictionary (remove all its items) with
    mydict.clear()
    print D     --> {}
    
  • If you have two dictionaries and you want to merge them, use the update method. It takes all the items in the second dictionary and inserts it into the first (or replaces it if the key exists).
    D1 = { 'A':'apple', 'B':'banana', 'C':'cat' }
    D2 = { 'D':'dog', 'B':'boy' }
    
    D1.update( D2 )
    print D1   --> { 'A':'apple', 'B':'boy', 'C':'cat', 'D':'dog' }
    
  • Note that like lists, if you attempt to index a dictionary with a key that doesn't exist you will get an error. Python also provides a get method which will instead give you a default value if it isn't in the dictionary.
    D = { 'A':'apple', 'B':'boy' }
    
    print D['A']                  --> 'apple'
    print D['R']                  --> error!
    
    print D.get( 'A' )            --> 'apple'
    print D.get( 'R' )            --> None
    print D.get( 'R', 'rabbit' )  --> 'rabbit'
    
  • To make an independent copy a dictionary you need to use the copy method. It you just copy the dictionary name you only create a new reference to the same dictionary. To see the difference examine,
    A = { 'state' : 'NY' }
    
    B = A
    C = A.copy()
    
    A['state'] = 'AZ'  # now change the original dict A
    
    print B   --> {'state':'AZ'}
    print C   --> {'state':'NY')