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?
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',)
Simply add a tuple to existing value
d={'Name': ('John', 'Mike'),
'Address': ('LA', 'NY')}
d["Name"]=d["Name"]+("lol",)
print d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With