简体   繁体   中英

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

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'}

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']
           )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM