Python-如何使用字典中的现有值将值添加到键? [英] Python - How to add values to a key with existing values in dictionary?

查看:707
本文介绍了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',)

这篇关于Python-如何使用字典中的现有值将值添加到键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆