简体   繁体   中英

Adding list of values in a value and key pair in python

I have a dictionary as below:

{'a':[(0,1),(1,1),(2,1),(0,2),(0,3)]}

So now I would like to obtain it in this way:

{'a':[(3,1),(0,2),(0,3)]}

So specifically I want to take the second element in the value list to be grouped by and the first element in the value list to give its sum.

from collections import defaultdict

dic = {'a': [(0,1),(1,1),(2,1),(0,2),(0,3)]}

newdic = {}
for k, v in dic.items():
    d = defaultdict(int)
    for vv in v:
        d[vv[1]] += vv[0]
    newdic[k] = [(v, k) for k, v in d.items()]
print(newdic)
# {'a': [(3, 1), (0, 2), (0, 3)]}
dictionary = {"a":[(0,1),(1,1),(2,1),(0,2),(0,3)]}

for k, l in dictionary.items():
    # have a temporary dictionary for each list
    temp_dictionary = dict()

    # for each tuple value, add the associated keys
    for tuple_k, tuple_v in l:
        # get(key, default_value_if_key_not_found)
        temp_dictionary[tuple_v] = temp_dictionary.get(tuple_v, 0) + tuple_k

    # replace the list in the original dictionary
    dictionary[k] = [(tuple_v, tuple_k) for (tuple_k, tuple_v) in temp_dictionary.items()]

print(dictionary)
# {a:[(3,1),(0,2),(0,3)]} 

Assuming the tuples in the arrays are ordered (or at least grouped) by the second value, you could use the groupby function from itertools to do the transformation:

from itertools import groupby

def group(tuples):
    return [ (sum(next(zip(*ts))),k) for k,ts in groupby(tuples,key=lambda t:t[1])]

d  = { "a":[(0,1),(1,1),(2,1),(0,2),(0,3)] }
d2 = { key:group(tuples) for key,tuples in d.items() }

# d2: {'a': [(3, 1), (0, 2), (0, 3)]}

if not, you'll have to sort them in the group function using:

tuples = sorted(tuples,key=lambda t:t[1])

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