Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary assignment during list comprehension

I have a dictionary of permissions as such:

{'READ': True,  'WRITE': None, 'DELETE': False}

The actual dictionary has more keys, but this suffices for the example. I would like to iterate over the dictionary and change any values of None to False. This can be done easily with a for loop, but I'm wondering if there's an idiomatic way to do it with a list comprehension. If it was an object instead of a dictionary I would just do:

[setattr(k, v, False) for k, v in object if v is None]

(or similar), but I'm not sure how to do it like that without using dict.__setitem__

This isn't super important to solve my problem, but I'm just wondering if there's a more concise way to do it

like image 223
axon Avatar asked Dec 20 '25 19:12

axon


1 Answers

Have you considered a dictionary comprehension:

>>> dct = {'READ': True,  'WRITE': None, 'DELETE': False}
>>> dct = {k:v if v is not None else False for k,v in dct.items()}
>>> dct
{'READ': True, 'WRITE': False, 'DELETE': False}
>>>

Note: If you are on Python 2.x, you should use dict.iteritems instead of dict.items. Doing so will improve efficiency since the former returns an iterator where as the later returns a list.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!