300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Python将新项添加到字典[重复]

Python将新项添加到字典[重复]

时间:2021-07-25 21:15:57

相关推荐

Python将新项添加到字典[重复]

本文翻译自:Python add new item to dictionary [duplicate]

This question already has an answer here:这个问题在这里已有答案:

Add new keys to a dictionary?在字典中添加新密钥?14 answers14个答案

I want to add an item to an existing dictionary in python.我想在python中将项添加到现有字典中。For example, this is my dictionary:例如,这是我的字典:

default_data = {'item1': 1,'item2': 2,}

I want to add new item such that:我想添加新项目,以便:

default_data = default_data + {'item3':3}

How to achieve this?怎么做到这一点?

#1楼

参考:/question/Qv7z/Python将新项添加到字典-重复

#2楼

default_data['item3'] = 3

Easy as py.很容易py。

Another possible solution:另一种可能的方案

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.如果你想一次插入多个项目,那就太好了。

#3楼

It can be as simple as:它可以很简单:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item.正如Chris的回答所说,您可以使用update来添加多个项目。An example:一个例子:

default_data.update({'item4': 4, 'item5': 5})

Please see the docs about dictionaries as data structures and dictionaries as built-in types .请将有关字典的文档视为数据结构和字典作为内置类型 。

#4楼

It occurred to me that you may have actually be asking how to implement the+operator for dictionaries, the following seems to work:我突然想到你可能实际上已经在询问如何为字典实现+运算符,以下似乎有效:

>>> class Dict(dict):...def __add__(self, other):... copy = self.copy()... copy.update(other)... return copy...def __radd__(self, other):... copy = other.copy()... copy.update(self)... return copy... >>> default_data = Dict({'item1': 1, 'item2': 2})>>> default_data + {'item3': 3}{'item2': 2, 'item3': 3, 'item1': 1}>>> {'test1': 1} + Dict(test2=2){'test1': 1, 'test2': 2}

Note that this is more overhead then usingdict[key] = valueordict.update(), so I would recommend against using this solution unless you intend to create a new dictionary anyway.请注意,这比使用dict[key] = valuedict.update()更有开销,所以我建议不要使用此解决方案,除非您打算创建一个新的字典。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。