Ankita Talwar
Ankita Talwar

Reputation: 121

efficient way to combine keys with same values in python dictionary

For example, I have the following dictionary

{'key1':value1,'key2':value2,'key3':value1,.......}} 

I want to change it to the following form:

{value1:[key1,key2],value2:[key3],....}

I have written the following to accomplish this task. However, I am not sure if this is the best way to go about it. Is there a better way to perform this task ?

node_cluster = {}

for node,cluster in zip(partition.keys(),partition.values()):
    if cluster not in node_cluster.keys():
        node_cluster[cluster] = []
    node_cluster[cluster].append(node)

Upvotes: 1

Views: 129

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You can use a collections.defaultdict to make the code a little bit shorter. A defaultdict(list) will automatically create an empty list as value when you try to access a key that doesn't exist yet :

from collections import defaultdict

d = {'a': 1, 'b': 2, 'c': 1}

out = defaultdict(list)
for k, v in d.items():
    out[v].append(k)
    
print(out)
# defaultdict(<class 'list'>, {1: ['a', 'c'], 2: ['b']})

Upvotes: 1

Related Questions