从另一个字典的值替换字典键

时间:2019-03-05 06:23:36

标签: python python-3.x dictionary

我有三个字典:

packed_items = {0: [0, 3],
                2: [1], 
                1: [2]}
trucks_dict = {0: [9.5, 5.5, 5.5],
               1: [13.0, 5.5, 7.0],
               2: [16.0, 6.0, 7.0]}
items_dict = {0: [4.6, 4.3, 4.3],
              1: [4.6, 4.3, 4.3],
              2: [6.0, 5.6, 9.0],
              3: [8.75, 5.6, 6.6]}

packed_items由卡车组成,键和值组成。我想更改我的packed_dict,使其以这种格式输出

packed_dict = {[9.5, 5.5, 5.5]:[[4.6, 4.3, 4.3],[8.75, 5.6, 6.6]]
               [16.0, 6.0, 7.0]:[[4.6, 4.3, 4.3]]
               [13.0, 5.5, 7.0]:[[6.0, 5.6, 9.0]]}

基本上,我想将packed_items中的键替换为trucks_dict中的值,并将packed_items中的值替换为items_dict中的值。

3 个答案:

答案 0 :(得分:1)

通过将列表键转换为元组,您可以执行以下操作:

代码:

result = {}
for k, v in packed_items.items():
    for i in v:
        result.setdefault(tuple(trucks_dict[k]), []).append(items_dict[i])

测试代码:

packed_items = {0: [0, 3],
                2: [1],
                1: [2]}
trucks_dict = {0: [9.5, 5.5, 5.5],
               1: [13.0, 5.5, 7.0],
               2: [16.0, 6.0, 7.0]}
items_dict = {0: [4.6, 4.3, 4.3],
              1: [4.6, 4.3, 4.3],
              2: [6.0, 5.6, 9.0],
              3: [8.75, 5.6, 6.6]}

result = {}
for k, v in packed_items.items():
    for i in v:
        result.setdefault(tuple(trucks_dict[k]), []).append(items_dict[i])
print(result)

结果:

{(9.5, 5.5, 5.5): [[4.6, 4.3, 4.3], [8.75, 5.6, 6.6]], 
 (16.0, 6.0, 7.0): [[4.6, 4.3, 4.3]], 
 (13.0, 5.5, 7.0): [[6.0, 5.6, 9.0]]
}

答案 1 :(得分:1)

您不能将列表用作字典键,因为它们不能散列。

因为您要求输入字符串键,所以您可以执行以下操作:

from collections import defaultdict

packed_items = {0: [0, 3],
                2: [1], 
                1: [2]}
trucks_dict = {0: [9.5, 5.5, 5.5],
               1: [13.0, 5.5, 7.0],
               2: [16.0, 6.0, 7.0]}
items_dict = {0: [4.6, 4.3, 4.3],
              1: [4.6, 4.3, 4.3],
              2: [6.0, 5.6, 9.0],
              3: [8.75, 5.6, 6.6]}

d = defaultdict(list)

for k1, v1 in trucks_dict.items():
    for k2, v2 in items_dict.items():
        if k1 == k2 % 3:
            d[str(v1)].append(v2)

print(d)
# {'[9.5, 5.5, 5.5]': [[4.6, 4.3, 4.3], [8.75, 5.6, 6.6]], '[16.0, 6.0, 7.0]': [[4.6, 4.3, 4.3]], '[13.0, 5.5, 7.0]': [[6.0, 5.6, 9.0]]}

答案 2 :(得分:0)

您可以使用dict理解将trucks_dict中的列表映射到items_dict中的项目。列表必须转换为元组,以便它们可以作为键散列:

{tuple(trucks_dict[k]): [items_dict[i] for i in l] for k, l in packed_items.items()}

这将返回:

{(9.5, 5.5, 5.5): [[4.6, 4.3, 4.3], [8.75, 5.6, 6.6]],
 (13.0, 5.5, 7.0): [[6.0, 5.6, 9.0]],
 (16.0, 6.0, 7.0): [[4.6, 4.3, 4.3]]}