I have a python dictionary
d = {1: 6, 2: 1, 3: 1, 4: 9, 5: 9, 6: 1}
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:
v = {6:[1], 1:[2, 3, 6], 9: [4, 5]}
Note the keys of new dictionary v should be sorted. I am finding it hard to visualize and implement this dictionary creation. Please suggest me an easy and efficient way to do it.
解决方案from collections import defaultdict
v = defaultdict(list)
for key, value in sorted(d.iteritems()):
v[value].append(key)
but you can do it with a bog-standard dict too:
v = {}
for key, value in sorted(d.iteritems()):
v.setdefault(value, []).append(key)
In Python 3, use sorted(d.items()) instead.