This code is not bad, but I want to know how good programmers will write the code
if count.get('a') is None:
count['a'] = 0
You can use dict.setdefault
:
count.setdefault('a', 0)
help on dict.setdefault
:
>>> print dict.setdefault.__doc__
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
setdefault
is the best answer, but for the record, the Pythonic way to check for a key in a dict
is using the in
keyword:
if 'a' not in count:
count['a'] = 0
Looking at the selection of answer, I believe the question is somewhat incorrectly phrased.
set a value in a dictionary if it is None?
In fact if the title is correct in asking about setting a value if it is None
, setdefault
doesn't set the value, instead returns that None
.
a_dict = {'key': None}
assert a_dict.setdefault('key', True) is None
I don't think it's a very common situation when you want to update the dictionary if a key has a value of None (as opposed to not having that key at all, in which case the setdefault
is the way to go.) or if it's not in there at all. In that case the following should work and seems the most pythonic to me.
if not a_dict.get('key'):
a_dict['key'] = 'value'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With