records = {'foo':foo, 'bar':bar, 'baz':baz}
I want to change the values to 0
if it is None
. How can I do this?
eg:
records = {'foo':None, 'bar':None, 'baz':1}
I want to change foo
and bar
to 0
. Final dict:
records = {'foo':0, 'bar':0, 'baz':1}
Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Change Dictionary Values in Python Using the dict. update() Method. In this method, we pass the new key-value pairs to the update() method of the dictionary object. We can change one and more key-value pairs using the dict.
for k in records: if records[k] is None: records[k] = 0
Another way
records.update((k, 0) for k,v in records.iteritems() if v is None)
Example
>>> records {'bar': None, 'baz': 1, 'foo': None} >>> records.update((k, 0) for k,v in records.iteritems() if v is None) >>> records {'bar': 0, 'baz': 1, 'foo': 0}
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