Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pythonically set a value in a dictionary if it is None?

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
like image 614
Vimos Avatar asked Sep 06 '13 17:09

Vimos


3 Answers

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
like image 95
Ashwini Chaudhary Avatar answered Oct 11 '22 12:10

Ashwini Chaudhary


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
like image 44
kindall Avatar answered Oct 11 '22 14:10

kindall


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'
like image 33
0xc0de Avatar answered Oct 11 '22 13:10

0xc0de