+4 votes
in Programming Languages by (60.0k points)
edited by
I have declared a python dictionary and now want to replace a key. How can I do that? Also, if the values are set/list, how can I replace just one value present in the set/list.

1 Answer

+1 vote
by (353k points)
selected by
Best answer

To replace an old key with a new value, do the following:

dictionary_name[new_key] = dictionary_name.pop(old_key)

Check this example:

>>> a={'aa':1,'bb':2}
>>> a.keys()
['aa', 'bb']
>>> a['aaa']=a.pop('aa')
>>> a
{'aaa': 1, 'bb': 2}
>>> a.items()
[('aaa', 1), ('bb', 2)]

Regarding ‚Äčthe second question: suppose you have the following dictionary with set and list as values and you want to replace one of the values in set/list with a new value. In the below code, I am replacing 1 by 3.

aa={'a':set([1,2,4]), 'b':4, 'c':[5,6,1]}
print ('Before change: {0}'.format(aa))
for k,v in aa.items():
        if 1 in v:
            if (type(v) is set):
            elif(type(v) is list):
print ('After change: {0}'.format(aa))