我有一本字典:
d = {0: 0, 1: 1, 2: 2, 3: 3, 4: 0, 5: 1, 6: 2, 7: 2, 8: 0, 9: 4, 10: 2, 11: 4, 12: 1, 13: 2, 14: 2, 15: 4, 16: 2}
我想计算每个值出现在字典中的数字: 即:
new_d_count = {0:3, 1:3, 2:7, ...}
我还想“翻转”它,使得每个值都是键,并且该新键的值将是原始列表的键。 即:
new_d = {0:(0,4,8), 1:(1,5,12), 2:(2,6,7,10,13,14,16) .....}
答案 0 :(得分:4)
使用Counter
解决您的第一个问题:
from collections import Counter
>>> Counter(d.values())
Counter({2: 7, 0: 3, 1: 3, 4: 3, 3: 1})
使用defaultdict
解决您的第二个问题:
>>> from collections import defaultdict
>>> new_d = defaultdict(tuple)
>>> for k,v in d.items():
... new_d[v] += (k,)
...
>>> new_d
defaultdict(<type 'tuple'>, {0: (0, 4, 8), 1: (1, 5, 12), 2: (2, 6, 7, 10, 13, 14, 16), 3: (3,), 4: (9, 11, 15)})
或者,没有defaultdict
:
>>> new_d = {}
>>> for k,v in d.items():
... new_d[v] = new_d.get(v, tuple()) + (k,)
...
>>> new_d
{0: (0, 4, 8), 1: (1, 5, 12), 2: (2, 6, 7, 10, 13, 14, 16), 3: (3,), 4: (9, 11, 15)}
最后,如果你真的不需要将值作为元组,那就这样做:
>>> new_d = {}
>>> for k,v in d.items():
... new_d.setdefault(v, []).append(k)
...
>>> new_d
{0: [0, 4, 8], 1: [1, 5, 12], 2: [2, 6, 7, 10, 13, 14, 16], 3: [3], 4: [9, 11, 15]}