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
In [4]:
dict["apple"]
Out[4]:
In [5]:
dict["mango"]
Out[5]:
You gen an exception when you try to access a key that is not defined...
In [6]:
dict["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]:
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
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]:
In [14]:
x.values()
Out[14]:
In [24]:
print x.has_key("apple")
print x.has_key("banana")
In [13]:
dir(x)
Out[13]:
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
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]