Cawr
Cawr

Reputation: 11

How to "sort" a dictionary by number of occurrences of a key?

I have a dictionary of values that gives the number of occurrences of a value in a list. How can I return a new dictionary that divides the former dictionary into separate dictionaries based on the value?

In other words, I want to sort this dictionary:

>>> a = {'A':2, 'B':3, 'C':4, 'D':2, 'E':3}

to this one.

b = {2: {'A', 'D'}, 3: {'B', 'E'}, 4: {'C'}}

How do I approach the problem?

Upvotes: 1

Views: 506

Answers (2)

Steve Deng Zishi
Steve Deng Zishi

Reputation: 128

if you are a python beginner like me, you probably wanna try this

a = {'A': 2 , 'B': 3 , 'C' : 4 , 'D' : 2, 'E' : 3}

b = {}

for key in a:

lst = []

new_key = a[key]

if new_key not in b:

    lst.append(key)

    b[new_key] = lst

else:

    b[new_key].append(key)

print(b)

It uses the mutable property of python dictionary to achieve the result you want.

Upvotes: 0

fenceop
fenceop

Reputation: 1497

from collections import defaultdict

a = {'A': 2, 'B': 3, 'C': 4, 'D': 2, 'E': 3}

b = defaultdict(set)
for k, v in a.items():
    b[v].add(k)

This is what you'll get:

defaultdict(<class 'set'>, {2: {'D', 'A'}, 3: {'B', 'E'}, 4: {'C'}})

You can convert b to a normal dict afterwards with b = dict(b).

Upvotes: 3

Related Questions