Fix Python – Python update a key in dict if it doesn’t exist

Question

Asked By – Xiaochen Cui

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?

Now we will see solution for issue: Python update a key in dict if it doesn’t exist


Answer

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.

This question is answered By – Martijn Pieters

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0