Adding a value to a specific key in a dictionary in Python

Viewed 233

I am new to Python. I am learning dictionary . I want to insert a new value to an existing dictionary. The existing dictionary is d={5:'acb',6:'bhg',7:'cssd'}. I want to add a new value 'xsd' at key no 5, but i am not able to do so. I have tried the below from my side. Please help.

d={5:'acb',6:'bhg',7:'cssd'}
d[5].append('xsd')
d

i want output as ; d={5:['acb','xsd'],6:'bhg',7:'cssd'}

2 Answers

You can try this:

d = {5: 'acb', 6: 'bhg', 7: 'cssd'}
if type(d[5]) is list:
    d[5].append('xsd')
else:
    tmp = []
    tmp.append(d[5])
    tmp.append('xsd')
    d[5] = tmp

You can use dict.pop

>>> d[5] = [d.pop(5), 'xsd']

From Python 3.8 onwards, you can make it more flexible using walrus operator:

>>> d[5] = ( [*value, 'xsd'] 
             if isinstance((value := d.pop(5)), list) 
             else [value, 'xsd']
           )
Related