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?
I'm sure you should use a
list
which is mutable as the value of the dictionary rather than atuple
which is immutable.Then,
d
isA tuple
()
is an immutable type which means you can't update its content. You should first convert that into alist
in order to mutate:Alternatively, you can create a new tuple from existing one along with the string that you want to add:
You can do
Don't forget
,
after `"NewName". Since you want to add it to tuple.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:
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 alist
are understood, as the difference is tiny and sometimes creates a confusion among the newcomers to Python. I apologize if it sounded rude.My advice would be to use a
defaultdict
of lists:That avoids the special case for initial list creation.
If you're using tuples you will have to recreate it each time as tuples are immutable:
But if you're going to append you better use list:
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
: