Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to add values to a key with existing values in dictionary?

First of all I'm a beginner in Python

I have this dictionary:

d={'Name': ('John', 'Mike'),
   'Address': ('LA', 'NY')}

Now I want to add more values in the keys like this.

d={'Name': ('John', 'Mike', 'NewName'),
   'Address': ('LA', 'NY', 'NewAddr')}

I tried update and append but I think it just works in list / tuples, and also I tried putting it in a list using d.items() and then overwriting the d dictionary but I think its messy and unnecessary?

Is there a direct method for python for doing this?

like image 465
Lee Song Avatar asked Dec 04 '25 18:12

Lee Song


2 Answers

A tuple () is an immutable type which means you can't update its content. You should first convert that into a list in order to mutate:

>>> d = {'Name': ['John', 'Mike'],
         'Address': ['LA', 'NY']}
>>> d['Name'].append('NewName')
>>> d['Address'].append('NewAddr') 

Alternatively, you can create a new tuple from existing one along with the string that you want to add:

>>> d['Name'] = d['Name'] + ('NewName',)
>>> d['Address'] = d['Address'] + ('NewAddr',)
like image 134
Ozgur Vatansever Avatar answered Dec 06 '25 06:12

Ozgur Vatansever


Simply add a tuple to existing value

d={'Name': ('John', 'Mike'),
  'Address': ('LA', 'NY')}

d["Name"]=d["Name"]+("lol",)
print d
like image 25
vks Avatar answered Dec 06 '25 08:12

vks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!