+4 votes
in Programming Languages by (56.8k 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 (349k 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():
    try:
        if 1 in v:
            v.remove(1)
            if (type(v) is set):
                aa[k].add(3)
            elif(type(v) is list):
                aa[k].append(3)
    except:
        continue
print ('After change: {0}'.format(aa))
 


...