Remove multiples values of a single key in python dictionary

147 Views Asked by At

I have a dictionary which has multiple values for a single key

myDict = {1: {'id1', 'id2', 'id3'}, 2: {'id4', 'id5'}, 3: {'id6'}}

My desired output is

myDict = {1: {'id1'}, 2: {'id4'}, 3: {'id6'}}

How do I only keep the first key and remove the rest?

1

There are 1 best solutions below

8
Anonymous12358 On

As comments mention, there is no "first" value in a set. However, there are several ways to get one item from a set.

You could use next(iter(v)) to get an arbitrary value in O(1) time. Eg:

myDict = {1: {'id1', 'id2', 'id3'}, 2: {'id4', 'id5'}, 3: {'id6'}}
result = {k: {next(iter(v))} for k, v in myDict.items()}
print(result)

This approach may choose a different item each time it is run. If you need to produce a consistent result, you could use eg min, as long as you're working with strings:

myDict = {1: {'id1', 'id2', 'id3'}, 2: {'id4', 'id5'}, 3: {'id6'}}
result = {k: {min(v)} for k, v in myDict.items()}
print(result)