Dictionary is another important data structure available in python. A dictionary stores key, value pairs. Basically, it implements a data structure known as a hash table. Lists need an index to lookup values. Dictionaries are different.. With dictionaries, you query a value using a "key". The "key" can be any immutable value


In [2]:
dict = { 
        "apple" : 10,
        "orange" : 20,
        "mango" : 50
        }
print dict


{'orange': 20, 'mango': 50, 'apple': 10}

In [4]:
dict["apple"]


Out[4]:
10

In [5]:
dict["mango"]


Out[5]:
50

You gen an exception when you try to access a key that is not defined...


In [6]:
dict["pineapple"]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/home/shkumar/python-workshop/<ipython-input-6-b4305a22d768> in <module>()
----> 1 dict["pineapple"]

KeyError: 'pineapple'

Adding a new value for a key is simple. And it's the same as updating an existing value.


In [7]:
dict["pineapple"] = 25
dict


Out[7]:
{'apple': 10, 'mango': 50, 'orange': 20, 'pineapple': 25}

You can't use a mutable value as a key. The following is OK, as a string is immutable.


In [8]:
x = "sapota:
dict[x] = 100

But the following won't work


In [9]:
x = [0]
dict[x] = 200


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/shkumar/python-workshop/<ipython-input-9-4151d1bb05a5> in <module>()
      1 x = [0]
----> 2 dict[x] = 200

TypeError: unhashable type: 'list'

Language note: this is true for in-built types, but not wholely accurate. It is possible to hash immutable values, if the object defines an __hash__ method! We won't cover this aspect in this workshop!

To get all the keys defined in a dictionary, use the keys() method. Likewise, use "values" to get the stored values. Note that the list returned by values() does not need to correspond to the key values returned by keys().


In [23]:
x = {"apple":10, "mango":20}
x.keys()


Out[23]:
['mango', 'apple']

In [14]:
x.values()


Out[14]:
[20, 10]

In [24]:
print x.has_key("apple")
print x.has_key("banana")


True
False

In [13]:
dir(x)


Out[13]:
['__class__',
 '__cmp__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'has_key',
 'items',
 'iteritems',
 'iterkeys',
 'itervalues',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values',
 'viewitems',
 'viewkeys',
 'viewvalues']

To remove an item from the dictionary, use pop. pop returns the value. del will remove the value.


In [22]:
x = {"hello":10, "yellow":20}
print x.pop("hello")
print x
del x['yellow']
print x


10
{'yellow': 20}
{}

A for loop on a dictionary iterates over the keys


In [25]:
likes = {"mango":50, "orange":20}
for fruit in likes:
    print 'I like ', fruit, ' factor = ', likes[fruit]


I like  orange  factor =  20
I like  mango  factor =  50