1

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    Try `for node,cluster in partition.items():` – Mike67 Oct 09 '20 at 21:15
  • This seems like a reasonable solution. You might consider using a [`collections.defaultdict(list)`](https://docs.python.org/3/library/collections.html#defaultdict-objects) to clean up some of the boilerplate. – 0x5453 Oct 09 '20 at 21:15
  • I think that's about as good as you can do. This question has an answer here: https://stackoverflow.com/a/485368/2860127 – Elliot Way Oct 09 '20 at 21:21

1 Answers1

1

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']})
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50