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
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.
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