Home > Net >  Way to remove reversed key:value pairs in python map dict?
Way to remove reversed key:value pairs in python map dict?

Time:10-30

I've look around pretty extensively and I'm either overlooking something or I haven't been able to find a solution for it. Usually I'd avoid making a post but I've been trying to figure this out for nearly two days now.

I'm still somewhat new to python so I may be overlooking something here:

I have this Dict:

dict = {'27': 28, '28': 27, '30' : 31, '31' : 30}

I want to remove duplicate keys:values reversed.

So for the final dict I would like:

dict = {'27': 28, '30' : 31}

So have at least one key:value pair for each duplicate.

I apologize if this is a duplicate post, but I have looked all around for an answer but haven't found anything of use or that I can wrap my head around.

Any help is much appreciated!

CodePudding user response:

For multiple keys:

data = {'27': 28, '28': 27, '30' : 31, '31' : 30}

seen = set()
seen_add = seen.update

data = {key: v for key, v in data.items() if not (((k := int(key)), v) in seen or seen_add(((k, v), (v, k))))}

{'27': 28, '30': 31}
  • Related