本文共 1692 字,大约阅读时间需要 5 分钟。
本文翻译自:
This question already has an answer here: 这个问题在这里已有答案:
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? 怎么做到这一点?
参考:
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. 如果你想一次插入多个项目,那就太好了。
It can be as simple as: 它可以很简单:
default_data['item3'] = 3
As says, you can use to add more than one item. 正如所说,您可以使用来添加多个项目。 An example: 一个例子:
default_data.update({'item4': 4, 'item5': 5})
Please see the docs about and . 请将有关的文档和 。
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 using dict[key] = value
or dict.update()
, so I would recommend against using this solution unless you intend to create a new dictionary anyway. 请注意,这比使用dict[key] = value
或dict.update()
更有开销,所以我建议不要使用此解决方案,除非您打算创建一个新的字典。
转载地址:http://lscnb.baihongyu.com/