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 a new item such that:
default_data = default_data + {'item3':3}
How can I achieve this?
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
There is no add() , append() , or insert() method you can use to add an item to a dictionary in Python. Instead, you add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With