Python-如何使用字典中的现有值将值添加到键?

Python-如何使用字典中的现有值将值添加到键?

问题描述:

首先,我是Python的初学者

First of all I'm a beginner in Python

我有这本字典:

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

我尝试了update和append,但是我认为它只适用于列表/元组,并且我尝试使用d.items()将其放入列表中,然后覆盖d字典,但是我认为它的混乱和不必要?

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?

是否有用于python的直接方法?

Is there a direct method for python for doing this?

元组()是不可变的类型,表示您无法更新其内容.您应该首先将其转换为list以便进行突变:

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',)