List of unique Python dict combination

I have big data. For rendering purpose this is an example of a dict as list,

Entrance:

a = [{'e1': 'a','e2': 'b'}, {'e1': 'b','e2': 'a'}, {'e1': 'a','e2': 'c'} ]

      

Output:

a = [{'e1': 'a','e2': 'b'}, {'e1': 'a','e2': 'c'}]

      

More details: If {'e1': 'a','e2': 'b'}

u {'e1': 'b','e2': 'a'}

point to every other value, I want it to be unique {'e1': 'a','e2': 'b'}

.

So basically e1 is the source and e2 is the target. if any link between source and target must be unique. Here already A linked to B, then it should not consider B linked to A.

+3


source to share


2 answers


You can try this

from itertools import groupby
[j.next() for i , j in groupby(a, lambda x: sorted(x.values()))

      



output:

[{'e1': 'a', 'e2': 'b'}, {'e1': 'a', 'e2': 'c'}]

      

+3


source


>>> dup_checker, output_a = [], []
>>> for dict_element in a:
       element_values = dict_element.values()
       element_values.sort()
       if  element_values not in dup_checker:
           output_a.append(dict_element)
           dup_checker.append(element_values)

>>> output_a
[{'e1': 'a', 'e2': 'b'}, {'e1': 'a', 'e2': 'c'}]

      



sort the dict element values ​​and create a dup_checker to track.

+4


source







All Articles