How to merge and sum value in dictionary based on key 1 and key 3 on tuple using Python

Viewed 40

I have several dictionaries

dict_1 = {('ABD12-GOU14', '4W', 'ASS 4W LINE 4', 80): [4, 5],
('ABD13-GOU14', '10W', 'ASS 4W LINE 5', 43): [2, 5],
('ABD14-GOU14', '11W', 'ASS 4W LINE 6', 90): [3, 5]}

dict_2 = {('ABD12-GOU14', '7W', 'ASS 4W LINE 4', 20): [5, 5],
('ABD13-GOU14', '2W', 'ASS 4W LINE 5', 31): [3, 5],
('ABD14-GOU14', '9W', 'ASS 4W LINE 5', 75): [2, 5]}

dict_3 = {('ABD12-GOU14', '23W', 'ASS 4W LINE 4', 20): [6, 5],
('ABD13-GOU14', '26W', 'ASS 4W LINE 5', 31): [2, 5],
('ABD14-GOU14', '6W', 'ASS 4W LINE 5', 75): [4, 5]}

Note: ('ABD12-GOU14', '23W', 'ASS 4W LINE 4', 20) => (keys1, keys2, keys3, keys4)

How can I sum dictionaries by matching tuples? I want it to look like this

{('ABD12-GOU14', 'ASS 4W LINE 4'):[15,5],
('ABD13-GOU14','ASS 4W LINE 5'):[7,5],
('ABD14-GOU14','ASS 4W LINE 5'):[6,5],
('ABD14-GOU14','ASS 4W LINE 6'):[3,5],
}
1 Answers

You should iterate over every dictionary and every key within that dictionary. Create a tuple from the key, and then add that to your new dictionary. Here is a code sample:

dict_1 = {('ABD12-GOU14', '4W', 'ASS 4W LINE 4', 80): [4, 5],
('ABD13-GOU14', '10W', 'ASS 4W LINE 5', 43): [2, 5],
('ABD14-GOU14', '11W', 'ASS 4W LINE 6', 90): [3, 5]}

dict_2 = {('ABD12-GOU14', '7W', 'ASS 4W LINE 4', 20): [5, 5],
('ABD13-GOU14', '2W', 'ASS 4W LINE 5', 31): [3, 5],
('ABD14-GOU14', '9W', 'ASS 4W LINE 5', 75): [2, 5]}

dict_3 = {('ABD12-GOU14', '23W', 'ASS 4W LINE 4', 20): [6, 5],
('ABD13-GOU14', '26W', 'ASS 4W LINE 5', 31): [2, 5],
('ABD14-GOU14', '6W', 'ASS 4W LINE 5', 75): [4, 5]}

new_dict = {}

for dic in [dict_1, dict_2, dict_3]:
    for key in dic:
        key_tuple = (key[0], key[2])
        if key_tuple not in new_dict:
            new_dict[key_tuple] = [0, 0]

        new_dict[key_tuple][0] += dic[key][0]
        new_dict[key_tuple][1] += dic[key][1]

print(new_dict)

Output:

{
    ("ABD12-GOU14", "ASS 4W LINE 4"): [15, 15],
    ("ABD13-GOU14", "ASS 4W LINE 5"): [7, 15],
    ("ABD14-GOU14", "ASS 4W LINE 6"): [3, 5],
    ("ABD14-GOU14", "ASS 4W LINE 5"): [6, 10],
}
Related