Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What if a key does not exist in dictionary Python?

If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.

Which method will add a key to the dictionary if it does not already exist in the dictionary?

Method 1: Add new keys using the Subscript notation This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it will be added and will point to that value. If the key exists, the current value it points to will be overwritten.

Can we update the key in dictionary Python?

We can easily do this by using update() function. The python update() method updates the dictionary with the key and value pairs. It inserts a key/value if it is not present. It updates the key/value if it is already present in the dictionary.

Can we update the value of a key in dictionary?

In order to update the value of an associated key, Python Dict has in-built method — dict. update() method to update a Python Dictionary. The dict. update() method is used to update a value associated with a key in the input dictionary.


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.


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'}

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.


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.