List duplicates manipulation

I am very new to python, and I am really lost right now. If anyone can help me, I will appreciate it a lot. I have a list:

list1 = [((a, b), 2), ((a, b), 5), ((c, d), 1)), ((e, f), 2), ((e, f), 4)]

The output I am looking for is:

output = [((a, b), 7), ((c, d), 1), ((e, f), 6)]

I tried to put it in a dictionary

new_dict = {i: j for i, j in list1}

But it throws me an error

Maybe there are other ways?


Find the explanation in the code comments

list1 = [(('a', 'b'), 2), (('a', 'b'), 5), (('c', 'd'), 1), (('e', 'f'), 2), (('e', 'f'), 4)]

# let's create an empty dictionary
output = {}

# ('a', 'b') is a tuple and tuple is hashable so we can use it as dictionary key
# iterate over the list1

for i in list1:
    # for each item check if i[0] exist in output
    if i[0] in output:
        # if yes just add i[1]
        output[i[0]] += i[1]
        # create new key
        output[i[0]] = i[1]
# finally print the dictionary
final_output = list(output.items())
[(('a', 'b'), 7), (('c', 'd'), 1), (('e', 'f'), 6)]

Leave a Reply

Your email address will not be published. Required fields are marked *