Python dictionary is a concept very similar to list but unlike list we can name the index of the data present in dictionary. Suppose we have list like this -
A=['jhon','gone','wild']
We have to write A[0] to get the value 'John' and so on.
But in the case of dictionary we can name A[0]='name'and access it's value with A['name'] and we get the value 'jhon'.
A=['jhon','gone','wild']
We have to write A[0] to get the value 'John' and so on.
But in the case of dictionary we can name A[0]='name'and access it's value with A['name'] and we get the value 'jhon'.
So the formal way to write a dictionary will be like this -
A={'name':’jhon','where':'gone','how':'wild ’}
Notice the second bracket unlike the third bracket of list.
A={'name':’jhon','where':'gone','how':'wild ’}
Notice the second bracket unlike the third bracket of list.
Lets have another dictionary and then iterate through the dictionary.
>>> a={'x':1,'y':2,'z':3}
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> for x in a:
print x,a[x]
y 2
x 1
z 3
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> for x in a:
print x,a[x]
y 2
x 1
z 3
The above for loop iterates through the dictionary and prints the keys and the values on it. Keys are the index of a particular value in a dictionary. Or you can also iterate through list by the iteritems() method.
for k,v in a.iteritems():
print k,v
print k,v
y 2
x 1
z 3
x 1
z 3
As you can see the results are the same.
Here are some other operations, you can do with dictionary -
>>> a['w']=4
>>> a
{'y': 2, 'x': 1, 'z': 3, 'w': 4}
>>> a.has_key('x')
True
>>> a.pop('w')
4
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> a.viewvalues()
dict_values([2, 1, 3])
>>> a.viewitems()
dict_items([('y', 2), ('x', 1), ('z', 3)])
>>> a.update()
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> a
{'y': 2, 'x': 1, 'z': 3, 'w': 4}
>>> a.has_key('x')
True
>>> a.pop('w')
4
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> a.viewvalues()
dict_values([2, 1, 3])
>>> a.viewitems()
dict_items([('y', 2), ('x', 1), ('z', 3)])
>>> a.update()
>>> a
{'y': 2, 'x': 1, 'z': 3}