如何将dict映射到另一个dict Python

时间:2015-09-09 15:12:06

标签: python dictionary

我有以下对的词典:

{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]}

2 个答案:

答案 0 :(得分:1)

class Account:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

dict1 = {0: Account(13,1), 1: Account(15,5), 2: Account(55,1), 3: Account(33,1)}
dict2 = {}
for key, val in dict1.iteritems():
    if val.p2 not in dict2:
        dict2[val.p2] = []
    dict2[val.p2].append(key)
print dict2

答案 1 :(得分: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]}