Dictionaries are unordered set of
key: value pairs where keys are unique. We declare dictionaries using {} braces. We use dictionaries to store data for any particular key and then retrieve them.
>>> data = {'kushal':'Fedora', 'kart_':'Debian', 'Jace':'Mac'}
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian'}
>>> data['kart_']
'Debian'
We can add more data to it by simply
>>> data['parthan'] = 'Ubuntu'
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
To delete any particular
key:value pair
>>> del data['kushal']
>>> data
{'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'
To check if any
key is there in the dictionary or not you can use
in keyword.
>>> 'Soumya' in data
False
You must remember that no mutable object can be a
key, that means you can not use a
list as a
key.
dict() can create dictionaries from tuples of
key,value pair.
>>> dict((('Indian','Delhi'),('Bangladesh','Dhaka')))
{'Indian': 'Delhi', 'Bangladesh': 'Dhaka'}
If you want to loop through a dict use
iteritems() method.
>>> data
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
>>> for x, y in data.iteritems():
... print "%s uses %s" % (x, y)
...
Kushal uses Fedora
Jace uses Mac
kart_ uses Debian
parthan uses Ubuntu
Many times it happens that we want to add more data to a value in a dictionary and if the key does not exists then we add some default value. You can do this efficiently using
dict.setdefault(key, default).
>>> data = {}
>>> data.setdefault('names', []).append('Ruby')
>>> data
{'names': ['Ruby']}
>>> data.setdefault('names', []).append('Python')
>>> data
{'names': ['Ruby', 'Python']}
>>> data.setdefault('names', []).append('C')
>>> data
{'names': ['Ruby', 'Python', 'C']}
When we try to get value for a key which does not exists we get
KeyError. We can use
dict.get(key, default) to get a default value when they key does not exists before.
>>> data['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> data.get('foo', 0)
0
If you want to loop through a list (or any sequence) and get iteration number at the same time you have to use
enumerate().
>>> for i, j in enumerate(['a', 'b', 'c']):
... print i, j
...
0 a
1 b
2 c
You may also need to iterate through two sequences same time, for that use
zip() function.
>>> a = ['Pradeepto', 'Kushal']
>>> b = ['OpenSUSE', 'Fedora']
>>> for x, y in zip(a, b):
... print "%s uses %s" % (x, y)
...
Pradeepto uses OpenSUSE
Kushal uses Fedora