How to update the value of a key in a dictionary in Python?



Python dictionary object is an unordered collection of key:value pairs. Ina dictionary object d, the value associated to any key can be obtained by d[k].

>>> d={'one':1, 'two':2,'three':3,'four':4}
>>> d['two']
2

The assignment d[k]=v will update the dictionary object. If existing key is used in the expression, its associated value will be updated. If the key has not been used, a new key-value pair will be added in the dictionary object.

>>> d={'one':1, 'two':2,'three':3,'four':4}
>>> d['two']=22
>>> d
{'one': 1, 'two': 22, 'three': 3, 'four': 4}
>>> d['five']=5
>>> d
{'one': 1, 'two': 22, 'three': 3, 'four': 4, 'five': 5}


Advertisements