Reputation: 83
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?
Upvotes: 2
Views: 185
Reputation: 52203
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',)
Upvotes: 6
Reputation: 3206
d['Name'] = d['Name'] + ('NewName',) # note the trailing comma!
Since tuples are immutable, you need to create a new tuple from the existing one by combining it with the new element into a new tuple. Or use a list instead of a tuple:
d = {'Name': ['John', 'Mike']}
d['Name'].append('NewName')
The second approach is preferable, because you don't create a new tuple each time you want to add a new name.
FWIW, for tuples you use normal parentheses ()
, and the angular ones []
for lists (the difference might not be immediately obvious if you are a beginner).
Edit: the last paragraph is by no means meant to be insulting or anything, it was written with good intentions, but could perhaps be reworded a bit. I just wanted to make sure the syntactic differences between creating a tuple
and a list
are understood, as the difference is tiny and sometimes creates a confusion among the newcomers to Python. I apologize if it sounded rude.
Upvotes: 0
Reputation: 14400
If you're using tuples you will have to recreate it each time as tuples are immutable:
d[key] = d.get(key, tuple()) + (newelm,)
But if you're going to append you better use list:
d = { "key1" : ["val1a", "val2a"],
"key2" : ["val2"] }
try:
d[key].append(newelm)
except KeyError:
d[key] = [newelm]
If you're sure the key already exists (or if it's an error if it doesn't) in the dict there's no need to use try
-except
:
d[key].append(newelm)
Upvotes: 0
Reputation: 149155
My advice would be to use a defaultdict
of lists:
import collections
d = collections.defaultdict(list)
d['Name'] += 'John'
d['Name'] += 'Mike'
print (d)
defaultdict(<type 'list'>, {'Name': ['John', 'Mike']})
That avoids the special case for initial list creation.
Upvotes: 1
Reputation: 2190
I'm sure you should use a list
which is mutable as the value of the dictionary rather than a tuple
which is immutable.
d={'Name': ['John', 'Mike'], 'Address': ['LA', 'NY']}
d['name'].append('NewName')
d['Address'].append('NewAddr')
Then, d
is
{'Name': ['John', 'Mike', 'NewName'], 'Address': ['LA', 'NY', 'NewAddr']}
Upvotes: 3
Reputation: 67988
Simply add a tuple
to existing value
d={'Name': ('John', 'Mike'),
'Address': ('LA', 'NY')}
d["Name"]=d["Name"]+("lol",)
print d
Upvotes: 5
Reputation: 1207
You can do
>>> d['Name'] += "NewName",
>>> d
{'Name': ('John', 'Mike', 'NewName'), 'Address': ('LA', 'NY')}
Don't forget ,
after `"NewName". Since you want to add it to tuple.
Upvotes: 1