0

I merged 2 lists and created new list which is having both lists data but im struck at cleaning my nested list.I need to remove duplicates keys and merge values for that duplicate key

list1 = [('ID1', 'Name'), ('ID2, 'Name'), ('ID2', 'team')]

expected output should be:
[('ID1', 'Name'), ('ID2, 'Name,team')]

2
  • you missed a quote after id2 in list1 Commented May 18, 2020 at 2:07
  • would a dictionary output be better than a list of tuples? Commented May 18, 2020 at 2:07

1 Answer 1

0

Here is the data as a dictionary which may be a bit easier to work with:

list1 = [('ID1', 'Name'), ('ID2', 'Name'), ('ID2', 'team')]

# create a dict with empty lists as keys
pivot = {i[0]: [] for i in list1}
for i in list1:
    # set the value of the first item key to the second item
    pivot[i[0]].append(i[1])

# converted to list of tuples, could be faster without doing the conversion
pivot_tuples = [(k, v) for k, v in pivot.items()]

print(f'dict: {pivot}')
print(f'tupl: {pivot_tuples}')

Output:

dict: {'ID1': ['Name'], 'ID2': ['Name', 'team']}
tupl: [('ID1', ['Name']), ('ID2', ['Name', 'team'])]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you :) and yes dictionary looks bit easier to work with
From where you are picking list_of_lists??
@vinay sorry, it should be list1 instead of list_of_lists, testing error. I edited the answer to refelct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.