All_Key
All_Key

Reputation: 11

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?

Upvotes: 1

Views: 63

Answers (3)

list1 = [(('a', 'b'), 2), (('a', 'b'), 5), (('c', 'd'), 1), (('e', 'f'), 2), (('e', 'f'), 4)]
sorted_dict = {}
for ele in list1:
    if ele[0] in sorted_dict:
        sorted_dict[ele[0]] += ele[1]
    else:
        sorted_dict[ele[0]] = ele[1]
print(sorted_dict)

Upvotes: 0

dawg
dawg

Reputation: 104111

You can use {}.get in this fashion:

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

di={}
for t in list1:
    di[t[0]]=di.get(t[0],0)+t[1]

>>> di
{('a', 'b'): 7, ('c', 'd'): 1, ('e', 'f'): 6}

You can also use a Counter:

from collections import Counter 

c=Counter({t[0]:t[1] for t in list1})

>>> c
Counter({('a', 'b'): 5, ('e', 'f'): 4, ('c', 'd'): 1})

Then to turn either of those into a list of tuples (as you have) you use list and {}.items():

>>> list(c.items())
[(('a', 'b'), 5), (('c', 'd'), 1), (('e', 'f'), 4)]

Upvotes: 1

Epsi95
Epsi95

Reputation: 9047

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]
    else:
        # create new key
        output[i[0]] = i[1]
        
# finally print the dictionary
final_output = list(output.items())
print(final_output)
[(('a', 'b'), 7), (('c', 'd'), 1), (('e', 'f'), 6)]

Upvotes: 1

Related Questions