Buddy Bob
Buddy Bob

Reputation: 5889

Find all keys with same unknown value

I've looked all over the internet asking the question how can I find all the keys in a dictionary that have the same value. But this value is not known. The closest thing that came up was this, but the values are known.

Say I had a dictionary like this and these values are totally random, not hardcoded by me.

{'AGAA': 2, 'ATAA': 5,'AJAA':2}

How can I identify all the keys with the same value? What would be the most efficient way of doing this.

['AGAA','AJAA']

Upvotes: 2

Views: 253

Answers (2)

Andreas
Andreas

Reputation: 9197

You can try this:

from collections import Counter

d = {'AGAA': 2, 'ATAA': 5,'AJAA':2}

l = Counter(d.values())
l = [x for x,y in l.items() if y > 1]

out = [x for x,y in d.items() if y in l]
# Out[21]: ['AGAA', 'AJAA']

Upvotes: 0

flakes
flakes

Reputation: 23624

The way I would do it is "invert" the dictionary. By this I mean to group the keys for each common value. So if you start with:

{'AGAA': 2, 'ATAA': 5, 'AJAA': 2}

You would want to group it such that the keys are now values and values are now keys:

{2: ['AGAA', 'AJAA'], 5: ['ATAA']}

After grouping the values, you can use max to determine the largest grouping.

Example:

from collections import defaultdict

data = {'AGAA': 2, 'ATAA': 5, 'AJAA': 2}

grouped = defaultdict(list)
for key in data:
    grouped[data[key]].append(key)

max_group = max(grouped.values(), key=len)
print(max_group)

Outputs:

['AGAA', 'AJAA']

You could also find the max key and print it that way:

max_key = max(grouped, key=lambda k: len(grouped[k]))
print(grouped[max_key])

Upvotes: 3

Related Questions