Rohan Nayani Rohan Nayani - 1 year ago 60
Python Question

Find duplicate value from list of tuples into python

How to find out duplicate value from following list of tuples?

[(1622, 4081), (1622, 4082), (1624, 4083) (1626, 4085), (1650, 4086), (1650, 4090)]

I want to get a list like


I have tried by itemgetter then group by option but can't succeed!

How to do that?

Answer Source

Use an ordered dictionary with first items as its keys and list of second items as values (for duplicates which created using dict.setdefalt()) then pick up those that have a length more than 1:

>>> from itertools import chain
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> for i, j in lst:
...     d.setdefault(i,[]).append(j)
>>> list(chain.from_iterable([j for i, j in d.items() if len(j)>1]))
[4081, 4082, 4086, 4090]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download