开发者

Is there a way to group several keys which points to the same value in a dictionary?

Is there a way to group several keys 开发者_如何学Gowhich points to the same value in a dictionary?


from collections import defaultdict

newdict = defaultdict(list)
for k,v in originaldict.items():
    newdict[v].append(k)


Not exactly sure you want the result structured, but here's one guess:

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}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜