Python add new item to dictionary [duplicate]

谁说胖子不能爱 提交于 2019-12-17 06:19:28

问题


I want to add an item to an existing dictionary in 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:


default_data['item3'] = 3

Easy as py.

Another possible solution:

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

which is nice if you want to insert multiple items at once.




回答2:


It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

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

Please see the docs about dictionaries as data structures and dictionaries as built-in types.




回答3:


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.



来源:https://stackoverflow.com/questions/6416131/python-add-new-item-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!