开发者

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

开发者 https://www.devze.com 2023-02-10 04:19 出处:网络
records = {\'foo\':foo, \'bar\':bar, \'baz\':baz} I want to change the values to 0 if it is None. How can I do this?
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, 'b开发者_开发技巧ar':0, 'baz':1}


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}


Try

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


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


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}


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 )
0

精彩评论

暂无评论...
验证码 换一张
取 消