Add a new item to a dictionary in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:26 Accepted answer (Score 1360)
00:45 Answer 2 (Score 93)
01:13 Answer 3 (Score 25)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/6416...
Answer 1 links:
[Chris' answer]: https://stackoverflow.com/questions/6416...
[update]: http://docs.python.org/library/stdtypes....
[dictionaries as data structures]: http://docs.python.org/tutorial/datastru...
[dictionaries as built-in types]: http://docs.python.org/library/stdtypes....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #items
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:26 Accepted answer (Score 1360)
00:45 Answer 2 (Score 93)
01:13 Answer 3 (Score 25)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/6416...
Answer 1 links:
[Chris' answer]: https://stackoverflow.com/questions/6416...
[update]: http://docs.python.org/library/stdtypes....
[dictionaries as data structures]: http://docs.python.org/tutorial/datastru...
[dictionaries as built-in types]: http://docs.python.org/library/stdtypes....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #items
#avk47
ACCEPTED ANSWER
Score 1376
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.
ANSWER 2
Score 96
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 documentation about dictionaries as data structures and dictionaries as built-in types.
ANSWER 3
Score 26
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.