Python - How to add values to a key with existing

2020-03-30 01:35发布

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?

7条回答
Emotional °昔
2楼-- · 2020-03-30 01:42

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']}
查看更多
看我几分像从前
3楼-- · 2020-03-30 01:45

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',)
查看更多
等我变得足够好
4楼-- · 2020-03-30 01:45

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.

查看更多
狗以群分
5楼-- · 2020-03-30 01:52
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.

查看更多
我只想做你的唯一
6楼-- · 2020-03-30 02:02

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.

查看更多
够拽才男人
7楼-- · 2020-03-30 02:02

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)
查看更多
登录 后发表回答