Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over and modify the values in a dict?

Tags:

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} 
like image 688
gomzi Avatar asked Feb 14 '11 13:02

gomzi


People also ask

Can you modify the value in a dictionary?

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.

Can you iterate over a dictionary?

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.

How do you change a value in a dictionary?

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.


2 Answers

for k in records:     if records[k] is None:         records[k] = 0 
like image 117
S.Lott Avatar answered Oct 13 '22 01:10

S.Lott


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} 
like image 41
Nick Dandoulakis Avatar answered Oct 13 '22 00:10

Nick Dandoulakis