677

How do I add an item to an existing dictionary in Python? For example, given:

default_data = {
    'item1': 1,
    'item2': 2,
}

I want to add a new item such that:

default_data = default_data + {'item3': 3}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
brsbilgic
  • 11,613
  • 16
  • 64
  • 94
  • 12
    http://docs.python.org/tutorial/datastructures.html#dictionaries – Ignacio Vazquez-Abrams Jun 20 '11 at 19:08
  • 26
    `default_data['item3'] = 3` isn't an option? – khachik Jun 20 '11 at 19:08
  • 4
    @machine yearning: http://meta.stackexchange.com/questions/5280/embrace-the-non-googlers – Fred Larson Jun 20 '11 at 19:15
  • 5
    i cant believe this inline solution hasn't been posted yet. We can use `{ **default_data, 'item3':3}` which returns the updated array. Very useful for lambda functions and list comprehensions. (requires [PEP 448](https://www.python.org/dev/peps/pep-0448/) (Python 3.5)) – GlabbichRulz Mar 14 '19 at 20:25
  • @GlabbichRulz: your solution is exactly the elegant approach I was hoping to find here - would you care to turn your comment into an answer so I can upvote it ? would also get me a direct link I can save for future reference... – ssc Jul 22 '20 at 16:02
  • @ssc i am afraid i can't do that, as the question is closed and accepts no further answers. You can use this link though to refer to my comment: https://stackoverflow.com/questions/6416131/add-a-new-item-to-a-dictionary-in-python?noredirect=1#comment97082105_6416131 – GlabbichRulz Jul 24 '20 at 10:52

3 Answers3

1363
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.

Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
  • 4
    Sorry for the thread necro, but is there any reason to prefer one method over the other when adding one item? – Warrick Feb 26 '13 at 14:01
  • 6
    @Warrick there's absolutely no difference except for personal taste. Personally I find the first to be a little more intuitive for just one item. – Chris Eberle Feb 26 '13 at 19:22
  • which is faster? – user3067923 Jul 08 '17 at 20:59
  • 2
    @user3067923 This is pure conjecture but I *imagine* that the first one would be marginally faster since it's mutating the dict in place, whereas the second one has to create a temporary dict, then mutate, then garbage collect the temporary dict. I'd need to benchmark it to say definitively. – Chris Eberle Sep 06 '17 at 23:35
  • @ChrisEberle and either should be O(1), or at least quite close to it, is that right? – user3067923 Sep 07 '17 at 22:56
  • @user3067923 even if it is O(n), how many items can your dictionary possibly have for it to matter? If it is that many, wouldn't a list and indexes be a better structure? – Arthur Tarasov Sep 04 '19 at 12:23
  • @ArthurTarasov forgive the snark but what exactly do you think a hash map is? Under the hood it *is* a "list and an index". That's the whole point of using one -- to abstract that away and focus on application logic. I'll grant you that there are other kinds of indices (e.g. B-Tree) -- but they're all better than O(n). If you're writing O(n) lookup procedures, I don't envy the people who have to use your code... – Chris Eberle Sep 05 '19 at 18:08
  • @Warrick - I had to use 2nd answer as it was within the list comprehension and I was unable to use '=' in it – rishi jain Aug 08 '21 at 14:33
94

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GreenMatt
  • 18,244
  • 7
  • 53
  • 79
25

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 3
    If you don't want to implement your own operators, you can also do `dict(default_data.items() + {'item3': 3}.items())` – Pakman Aug 23 '13 at 13:56
  • 1
    @Pakman's comment doesn't work in Python3 (see: http://stackoverflow.com/questions/13361510/typeerror-unsupported-operand-types-for-dict-items-and-dict-items/13361547#13361547) – Prof Feb 21 '16 at 21:15
  • 1
    For Python 3, a quick fix to still use @Pakman comment is to cast the output of `dict.items()` in a `list` as follows: `dict(list(default_data.items()) + list({'item3': 3}.items()))`, or even use the more idomatic: `{**default_data, **{'item3': 3}}` – H. Rev. Dec 17 '19 at 15:37