This question already has an answer here:
- Add new keys to a dictionary? 14 answers
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?
It can be as simple as:
As Chris' answer says, you can use update to add more than one item. An example:
Please see the docs about dictionaries as data structures and dictionaries as built-in types.
It occurred to me that you may have actually be asking how to implement the
+
operator for dictionaries, the following seems to work:Note that this is more overhead then using
dict[key] = value
ordict.update()
, so I would recommend against using this solution unless you intend to create a new dictionary anyway.answer must be so long.
Easy as py.
Another possible solution:
which is nice if you want to insert multiple items at once.