Python update a key in dict if it doesn't exist

PythonDictionary

Python Problem Overview


I want to insert a key-value pair into dict if key not in dict.keys(). Basically I could do it with:

if key not in d.keys():
    d[key] = value

But is there a better way? Or what's the pythonic solution to this problem?

Python Solutions


Solution 1 - Python

You do not need to call d.keys(), so

if key not in d:
    d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.

Solution 2 - Python

Use dict.setdefault():

>>> d = {'key1': 'one'}
>>> d.setdefault('key1', 'some-unused-value')
'one'
>>> d    # d has not changed because the key already existed
{'key1': 'one'}
>>> d.setdefault('key2', 'two')
'two'
>>> d
{'key1': 'one', 'key2': 'two'}

Solution 3 - Python

Since Python 3.9 you can use the merge operator | to merge two dictionaries. The dict on the right takes precedence:

new_dict = old_dict | { key: val }

For example:

new_dict = { 'a': 1, 'b': 2 } | { 'b': 42 }

print(new_dict) # {'a': 1, 'b': 42}

Note: this creates a new dictionary with the updated values.

Solution 4 - Python

With the following you can insert multiple values and also have default values but you're creating a new dictionary.

d = {**{ key: value }, **default_values}

I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .

Speed test comparing a for loop based method with a dict comprehension with unpack operator Speed test comparing a for loop based method with a dict comprehension with unpack operator method.

if no copy (d = default_vals.copy()) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5 and greater. Memory footprint of both methods are the same.

Solution 5 - Python

You can also use this solution in only one line of code:

dict[dict_key] = dict.get(dict_key,value)

The second argument of dict.get is the value you want to assign to the key in case the key does not exist. Since this evaluates before the assignment to dict[dict_key] = , we can be sure that they key will exist when we try to access it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXiaochen CuiView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonmhawkeView Answer on Stackoverflow
Solution 3 - PythonRotaretiView Answer on Stackoverflow
Solution 4 - PythonCoderKidView Answer on Stackoverflow
Solution 5 - PythonBirthday CatView Answer on Stackoverflow