简体   繁体   中英

How to replace dict values with their sum

I have a result set that is in form of a list of dict s (sample data below):

l = [
  {'id' : 1, 'desc' : 'foo', 'v1' : 1, 'v2' : 2},
  {'id' : 2, 'desc' : 'bar', 'v1' : 3, 'v2' : 4},
  {'id' : 3, 'desc' : 'baz', 'v1' : 5, 'v2' : 6}
]

I want to convert this to a form where v1 and v2 are added up and replaced by their summed up value. So the result will look like:

[
  {'id' : 1, 'desc' : 'foo', 'v' : 3},
  {'id' : 2, 'desc' : 'bar', 'v' : 7},
  {'id' : 3, 'desc' : 'baz', 'v' : 11}
 ]

Please suggest the best way to do this in python 3.2.

EDIT:

Here's what I have:

for d in l: d['v'] = d.pop('v1') + d.pop('v2')

I don't like the part with the pop() s and would like to get rid of these and also compress all of it in one line, if possible.

What about...

def sum_v1_v2_into_v(list_of_dicts):
    for d in list_of_dicts:
        v1 = d.pop('v1')
        v2 = d.pop('v2')
        d['v'] = v1 + v2

Seems pretty much the obvious approach, right?

If for some totally weird and unexplained reason you want to "compress it into one line, then collapse the last 3 lines to the less-obvious single line:

        d['v'] = d.pop('v1') + d.pop('v2')

but I fail to see any real advantage -- are you having to pay X per line of code you write, or what?-)

In one line:

[each.update({'v': each.pop('v1')+each.pop('v2')}) for each in l]

It will return:

[None, None, None]

but It will update the dict called "l" to

[{'desc': 'foo', 'id': 1, 'v': 3},

{'desc': 'bar', 'id': 2, 'v': 7},

{'desc': 'baz', 'id': 3, 'v': 11}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM