简体   繁体   中英

Remove duplicates from dictionary of tuples

I have the following dictionary, that consists of Keys: list of tuples as values

{0: [(1410.0, 21.77562368178597), (1400.0, 19.207664561646514), (1400.0, 0.0008002910625641847), (1390.0, 0.005384339399360756), (1390.0, 16.81119144715727), (1380.0, 0.006317587214078991), (1380.0, 14.581397723675186), (1370.0, 12.425676833176958), (1360.0, 10.157186391679849), (1350.0, 8.464056857473565), (1340.0, 6.743908971063571), (1330.0, 4.886783322196731), (1320.0, 3.712576730302521), (1310.0, 2.689847385668083), (1300.0, 1.6219146729959537), (1290.0, 0.41216337921204677)], ....etc)

In some cases there are tuples that have same first element but different second element. In the example from the code above (1400, 19.2) & (1400, 0.0000000000291)

What I want to do is to combine these tuples into one tuple (1400, (sum of the second element)

Is this what you mean?

Suppose that d is the name of your dictionary.

d = {0: [(1410.0, 21.77562368178597), (1400.0, 19.207664561646514), (1400.0, 0.0008002910625641847), (1390.0, 0.005384339399360756), (1390.0, 16.81119144715727), (1380.0, 0.006317587214078991), (1380.0, 14.581397723675186), (1370.0, 12.425676833176958), (1360.0, 10.157186391679849), (1350.0, 8.464056857473565), (1340.0, 6.743908971063571), (1330.0, 4.886783322196731), (1320.0, 3.712576730302521), (1310.0, 2.689847385668083), (1300.0, 1.6219146729959537), (1290.0, 0.41216337921204677)]}

Now try this code:

new_d = {}
for item in d:
    summations = {}
    for key, value in d[item]:
        if key in summations:
            summations[key] += value
        else:
            summations[key] = value
    temp_list = []
    for key in summations:
        temp_list.append((key, summations[key]))
    new_d[item] = temp_list
print(new_d)

first Idea that i got is 2 for loops in the first one you take the first number from the current tuple and in the second for loop you compare it to each first number of the elemet in the dic. If it matches than you take the second number from that element from that tuple and add it to the one from the first for loop.Than you delete the tuple in the second loop.You could also save each key for all tuples that have duplicate first number and delate them in the next step There might be a better solution for this but this is what i would try if Performance is not important

s = set()
[s.add(t) for t in dict_of_tuples.values()]

Demo:

>>> dict_of_tuples = tuple([1,2,(3,3), (3, 3)]
{1, 2, (3, 3), (3,3)}
>>> s = set()
>>> [s.add(t) for t in dict_of_tuples.values()]
(1, 2, (3,3))

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