gomzi
gomzi

Reputation: 267

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

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}

Upvotes: 23

Views: 46094

Answers (6)

S.Lott
S.Lott

Reputation: 391818

records = dict( ( k,0 if v is None else v ) for k, v in records.items() )

def zero_if_none( x ):
    return 0 if x is None else x
records = dict( ( k, zero_if_none( records[k] ) ) for k in records )

Upvotes: 0

Deestan
Deestan

Reputation: 17138

If you want to intimidate or annoy other code maintainers, there's an ugly one-liner that will do the trick:

records.update(map(lambda (k,v):(k,{v:v,None:0}[v]), records.items()))

Example use:

>>> records = {"hey":None, "you":0}
>>> records.update(map(lambda (k,v):(k,{v:v,None:0}[v]), records.items()))
>>> records
{'you': 0, 'hey': 0}

Upvotes: 2

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43110

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}

Upvotes: 19

S.Lott
S.Lott

Reputation: 391818

for k in records:
    if records[k] is None:
        records[k] = 0

Upvotes: 21

Alex Reynolds
Alex Reynolds

Reputation: 96927

for k, v in records.items():
    if v is None:
        records[k] = 0

Upvotes: 9

Sven Marnach
Sven Marnach

Reputation: 601489

Try

for key, value in records.iteritems():
    if value is None:
        records[key] = 0

Upvotes: 13

Related Questions