Skip to content
Advertisement

Grouping Python dictionary keys as a list and create a new dictionary with this list as a value

I have a python dictionary

JavaScript

Since the values in the above dictionary are not unique, I want to group the all the keys of unique values as a list and create a new dictionary as follows:

JavaScript

Note the keys of new dictionary v should be sorted. I am finding it hard to visualize and implement this dictionary creation.

Advertisement

Answer

Using collections.defaultdict for ease:

JavaScript

but you can do it with a bog-standard dict too, using dict.setdefault():

JavaScript

The above sorts keys first; sorting the values of the output dictionary later is much more cumbersome and inefficient.

If anyone would not need the output to be sorted, you can drop the sorted() call, and use sets (the keys in the input dictionary are guaranteed to be unique, so no information is lost):

JavaScript

to produce:

JavaScript

(that the output of the set values is sorted is a coincidence, a side-effect of how hash values for integers are implemented; sets are unordered structures).

Advertisement