2

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

3
  • d[5] = d[5] + 'xsd' Commented Jun 2, 2021 at 5:59
  • i want them as separate elements as the following : d={5:['acb','xsd'],6:'bhg',7:'cssd'} Commented Jun 2, 2021 at 6:00
  • 1
    if i m adding using + operator i m getting the following : {5: 'acbxsd', 6: 'bhg', 7: 'cssd'} Commented Jun 2, 2021 at 6:01

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@ChayanMehrotra welcome. Please accept the answer if it is working.
1

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

3 Comments

If you could explain this ? pop() method removes the particular value from a key, after that how it is working ?
You pop the value of the key (eg. 'acb'), and put it in a list with xsd, so [d.pop(5), 'xsd'] is essentially ['acb', 'xsd'], and you assign it back to d[5]
@ChayanMehrotra The pop() method removed the value d[5] from the dict, and returns the value ('acb' in the given case). Then the value ['acb', 'xsd'] is stored as d[5]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.