有没有办法将几个指向字典中相同值的键分组?
答案 0 :(得分:3)
from collections import defaultdict
newdict = defaultdict(list)
for k,v in originaldict.items():
newdict[v].append(k)
答案 1 :(得分:2)
不完全确定您希望结果是否结构化,但这是一个猜测:
from collections import defaultdict
mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 4, 'f': 2, 'g': 4}
tempdict = defaultdict(list)
for k,v in mydict.iteritems():
tempdict[v].append(k)
groupedkeysdict = {}
for k,v in tempdict.iteritems():
groupedkeysdict[tuple(v) if len(v)>1 else v[0]] = k
print groupedkeysdict
# {'a': 1, 'c': 3, ('e', 'g'): 4, ('b', 'd', 'f'): 2}