我有以下几对字典:
{0: Account(13, 1), 1: Account(15, 5), 2: Account(55, 1), 3: Account(33 ,1)}
我想重新映射它,并得到以下字典
{second_value_of_dict1: list[index_of_dict1]}
例子:
{1: [0, 2, 3], 5: [1]}
您可以使用defaultdict
以下方法:
class Account:
def __init__(self, x, y):
self.x = x
self.y = y
d_in = {0: Account(13, 1), 1: Account(15, 5), 2: Account(55, 1), 3: Account(33 ,1)}
d_out = collections.defaultdict(list)
for index, k in enumerate(d_in.keys()):
d_out[d_in[k].y].append(index)
print d_out
提供以下输出:
defaultdict(<type 'list'>, {1: [0, 2, 3], 5: [1]})
如果您真的希望它看起来像常规的,dict
那么:
print dict(d_out)
给予:
{1: [0, 2, 3], 5: [1]}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句