By lfaraone


2009-06-21 22:07:39 8 Comments

Is it possible to add a key to a Python dictionary after it has been created?

It doesn't seem to have an .add() method.

16 comments

@Yugal Jindle 2011-12-05 06:07:36

I feel like consolidating info about Python dictionaries:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

Inserting/Updating a single value

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

Inserting/Updating multiple values

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

Create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))

New to Python 3.5

Creating a merged dictionary without modifying originals:

This uses a new featrue called dictionary unpacking.

data = {**data1, **data2, **data3}

New to Python 3.9

Update or add values for an existing dictionary

The update operator |= now works for dictionaries:

data |= {'c':3,'d':4}

Creating a merged dictionary without modifying originals

The merge operator | now works for dictionaries:

data = data1 | {'c':3,'d':4}

Feel free to add more!

@user142911 2009-07-22 14:48:17

To add multiple keys simultaneously, use dict.update():

>>> x = {1:2}
>>> print(x)
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print(x)
{1: 2, 3: 4, 5: 6, 7: 8}

For adding a single key, the accepted answer has less computational overhead.

@Jean-François Fabre 2018-08-01 21:42:49

this is soooo inefficient to create a dictionary just to update one key. Do this only if you have more than 1 key (there may be a threshold above which it's better to create a dict)

@Robert Brisita 2019-03-27 05:59:04

@Jean-FrançoisFabre This is example code. You really shouldn't treat answers as covering all cases.

@Jean-François Fabre 2019-03-27 06:14:36

it gives the wrong impression that it's the preferred way to add one key.

@ingyhere 2020-01-20 16:10:45

@Jean-FrançoisFabre Since dict ordering is guaranteed in Python 3.7+ (and provided in 3.6+), this may well be a preferred way to add a single key when order is important.

@Jean-François Fabre 2020-01-20 16:26:19

if you create another key like x[-1] = 44 the -1 value is in the end too. Anyway answer has been edited and is much better now. Updating with a dictionary is good when it's likely that it contains many items.

@Susan 2020-02-04 01:47:50

add dictionary key, value class.

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        #self[key] = value # add new key and value overwriting any exiting same key
        if self.get(key)!=None:
            print('key', key, 'already used') # report if key already used
        self.setdefault(key, value) # if key exit do nothing


## example

myd = myDict()
name = "fred"

myd.add('apples',6)
print('\n', myd)
myd.add('bananas',3)
print('\n', myd)
myd.add('jack', 7)
print('\n', myd)
myd.add(name, myd)
print('\n', myd)
myd.add('apples', 23)
print('\n', myd)
myd.add(name, 2)
print(myd)

@Paolo Bergantino 2009-06-21 22:09:06

d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}

@R. Navega 2018-05-31 01:22:07

The explanation is: you create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.

@hegash 2019-01-16 19:14:17

What is the difference between this and the .update() method? Which is better when?

@bgusach 2019-02-13 08:38:56

@hegash the d[key]=val syntax as it is shorter and can handle any object as key (as long it is hashable), and only sets one value, whereas the .update(key1=val1, key2=val2) is nicer if you want to set multiple values at the same time, as long as the keys are strings (since kwargs are converted to strings). dict.update can also take another dictionary, but I personally prefer not to explicitly create a new dictionary in order to update another one.

@Sma Ma 2019-12-13 14:47:13

try it, here is an example: repl.it/@SmaMa/Add-key-to-dict

@Juan-Kabbali 2020-04-28 12:55:19

how can i add an element in a nested dict. Like php $foo[ ] = [ . . . . ]

@ingyhere 2019-11-19 04:57:20

Here's another way that I didn't see here:

>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}

You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!

>>> foo = dict(a=1,b=2,c=3,d=4)
>>> new_dict = {k: v for k, v in list(foo.items())[:2]}
>>> new_dict
{'a': 1, 'b': 2}
>>> new_dict.update(newvalue=99)
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99}
>>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
>>> 

The above is using dictionary comprehension.

@kiriloff 2013-05-25 13:33:35

You can create one:

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        self[key] = value

## example

myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)

Gives:

>>> 
{'apples': 6, 'bananas': 3}

@m_____z 2019-08-27 21:21:02

I think it would also be useful to point out Python's collections module that consists of many useful dictionary subclasses and wrappers that simplify the addition and modification of data types in a dictionary, specifically defaultdict:

dict subclass that calls a factory function to supply missing values

This is particularly useful if you are working with dictionaries that always consist of the same data types or structures, for example a dictionary of lists.

>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})

If the key does not yet exist, defaultdict assigns the value given (in our case 10) as the initial value to the dictionary (often used inside loops). This operation therefore does two things: it adds a new key to a dictionary (as per question), and assigns the value if the key doesn't yet exist. With the standard dictionary, this would have raised an error as the += operation is trying to access a value that doesn't yet exist:

>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key'

Without the use of defaultdict, the amount of code to add a new element would be much greater and perhaps looks something like:

# This type of code would often be inside a loop
if 'key' not in example:
    example['key'] = 0  # add key and initial value to dict; could also be a list
example['key'] += 1  # this is implementing a counter

defaultdict can also be used with complex data types such as list and set:

>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})

Adding an element automatically initialises the list.

@Colonel Panic 2013-04-14 00:58:27

The orthodox syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could do:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php

@Bobort 2016-10-27 14:10:02

I would find it extremely difficult to program with python without the bracket keys on my keyboard.

@chris stevens 2018-05-18 13:29:31

This was the only way I could find to set dictionary values within a list comprehension. Thanks

@Jeremy Logan 2018-09-13 22:45:39

@chrisstevens if you want to set a value in a comprehension a hack I've used is [a for a in my_dict if my_dict.update({'a': 1}) is None].

@Aleister Tanek Javas Mraz 2019-08-13 16:47:46

Curious... is this (i.e.- missing square brackets) common ?

@ingyhere 2020-01-20 16:22:38

@chrisstevens @JeremyLogan Why use a list comprehension when you can use a dict comprehension? {v: k for k, v in my_dict.items() if <some_conditional_check>}

@Agus Mathew 2019-03-25 13:01:25

first to check whether the key already exists

a={1:2,3:4}
a.get(1)
2
a.get(5)
None

then you can add the new key and value

@Burak Özdemir 2018-10-11 08:57:34

If you're not joining two dictionaries, but adding new key-value pairs to a dictionary, then using the subscript notation seems like the best way.

import timeit

timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254

timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383

However, if you'd like to add, for example, thousands of new key-value pairs, you should consider using the update() method.

@campeterson 2018-01-12 19:31:53

Let's pretend you want to live in the immutable world and do NOT want to modify the original but want to create a new dict that is the result of adding a new key to the original.

In Python 3.5+ you can do:

params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}

The Python 2 equivalent is:

params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})

After either of these:

params is still equal to {'a': 1, 'b': 2}

and

new_params is equal to {'a': 1, 'b': 2, 'c': 3}

There will be times when you don't want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3

or

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})

Reference: https://stackoverflow.com/a/2255892/514866

@campeterson 2018-01-30 17:05:21

In a lengthy conversation with a pro-functional programming colleague of mine a good point was brought up. One downside to the above approach is that if someone reading the code is not familiar with the ** in Python (many aren't) then it won't be obvious what is going on. There are times when you'll favor a less functional approach for better readability.

@Gabriel 2018-03-07 20:56:41

We cannot foresee what subset of the Python language our readers know, so it's fair to assume they know the entire language so they search on the docs for the parts they don't.

@Asher 2012-04-26 19:04:33

If you want to add a dictionary within a dictionary you can do it this way.

Example: Add a new entry to your dictionary & sub dictionary

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

Output:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

NOTE: Python requires that you first add a sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.

@Erik Kaplun 2012-06-01 21:05:40

this is as irrelevant to the question asked as most of the comments in php.net manual pages...

@Chris 2017-12-27 16:07:22

Nothing to stop you doing this on one line: dictionary = {"dictionary_within_a_dictionary": {"sub_dict": {"other" : "dictionary"}}} (or if dictionary is already a dict, dictionary["dictionary_within_a_dictionary"] = {"sub_dict": {"other" : "dictionary"}})

@Michael Ekoka 2017-10-23 14:03:24

So many answers and still everybody forgot about the strangely named, oddly behaved, and yet still handy dict.setdefault()

This

value = my_dict.setdefault(key, default)

basically just does this:

try:
    value = my_dict[key]
except KeyError: # key not found
    value = my_dict[key] = default

e.g.

>>> mydict = {'a':1, 'b':2, 'c':3}
>>> mydict.setdefault('d', 4)
4 # returns new value at mydict['d']
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # a new key/value pair was indeed added
# but see what happens when trying it on an existing key...
>>> mydict.setdefault('a', 111)
1 # old value was returned
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # existing key was ignored

@Aaron Hall 2014-11-29 23:57:59

"Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method."

Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.

To demonstrate how and how not to use it, let's create an empty dict with the dict literal, {}:

my_dict = {}

Best Practice 1: Subscript notation

To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:

my_dict['new key'] = 'new value'

my_dict is now:

{'new key': 'new value'}

Best Practice 2: The update method - 2 ways

We can also update the dict with multiple values efficiently as well using the update method. We may be unnecessarily creating an extra dict here, so we hope our dict has already been created and came from or was used for another purpose:

my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})

my_dict is now:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}

Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict:

my_dict.update(foo='bar', foo2='baz')

and my_dict is now:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}

So now we have covered three Pythonic ways of updating a dict.


Magic method, __setitem__, and why it should be avoided

There's another way of updating a dict that you shouldn't use, which uses the __setitem__ method. Here's an example of how one might use the __setitem__ method to add a key-value pair to a dict, and a demonstration of the poor performance of using it:

>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}


>>> def f():
...     d = {}
...     for i in xrange(100):
...         d['foo'] = i
... 
>>> def g():
...     d = {}
...     for i in xrange(100):
...         d.__setitem__('foo', i)
... 
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539

So we see that using the subscript notation is actually much faster than using __setitem__. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.

@holdenweb 2020-02-05 13:41:06

The difference is rather less marked in 2020 (on my machine, 1.35 ms subscripting vs 2ms for d.__setitem__), though the conclusion (and especially the last sentence) remains sound. Hoisting the method name lookup out of the loop reduced time to about 1.65 ms; the remaining difference is likely largely due to unavoidable Python call mechanism overhead.

@nobar 2013-08-17 23:04:12

This popular question addresses functional methods of merging dictionaries a and b.

Here are some of the more straightforward methods (tested in Python 3)...

c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

Note: The first method above only works if the keys in b are strings.

To add or modify a single element, the b dictionary would contain only that one element...

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

This is equivalent to...

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )

@nobar 2013-08-17 23:09:03

Interesting comment about the first method from Python's BDFL (here).

@holdenweb 2020-02-05 13:51:30

c = dict( a, **{'d':'dog'} ) would be better written as c = dict(a, d='dog'), as long as keys are known and not computed.

@Jason Creighton 2009-06-21 22:08:57

dictionary[key] = value

Related Questions

Sponsored Content

45 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression in Python?

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

20 Answered Questions

[SOLVED] Are static class variables possible in Python?

12 Answered Questions

[SOLVED] How to remove a key from a Python dictionary?

10 Answered Questions

[SOLVED] Static methods in Python?

11 Answered Questions

[SOLVED] Iterating over dictionaries using 'for' loops

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

13 Answered Questions

[SOLVED] Create a dictionary with list comprehension

16 Answered Questions

[SOLVED] Check if a given key already exists in a dictionary

  • 2009-10-21 19:05:09
  • Mohan Gulati
  • 3584761 View
  • 2683 Score
  • 16 Answer
  • Tags:   python dictionary

Sponsored Content