2

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?

5
  • can you show us the code please Commented Aug 14, 2015 at 7:01
  • 1
    First of all the value is a tuple you can not append to tuple Commented Aug 14, 2015 at 7:02
  • I declared the initial items (john, mike and la, ny) Commented Aug 14, 2015 at 7:03
  • 2
    a simple question and there is a tsunami of answers :P same like there is a naive customer in a huge marker Commented Aug 14, 2015 at 7:03
  • 1
    Bam! Lots of similar answers on this one; I saw them in time before posting mine :P. Commented Aug 14, 2015 at 7:04

7 Answers 7

6

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

Comments

5

Simply add a tuple to existing value

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

d["Name"]=d["Name"]+("lol",)
print d

Comments

3

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

Comments

1

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.

Comments

1

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.

Comments

0

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)

4 Comments

It would be nice if when downvoting an answer there were an explaination to why it was downvoted - that way I could improve my answer.
I didn't downvote but d.get(key, tuple() + (newelm, ) throws syntax error.
@ozgur Thank's for the feedback, I've added the missing parenthesis.
It's easy to fire a downvote and forget about it, but it takes a bit more effort to explain, why an answer is incomplete and/or how it could be improved. It sometimes tells more about the downvoter than the answer itself. Your answer was fine, @skyking, syntax errors happen.
0
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.

Comments

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.