首页 > 解决方案 > 将 python 字典中的值推送到第二个字典的相应键值

问题描述

我正在编写的程序中有两个字典,以便练习在 Python 中处理 .jsons。我希望我的程序获取任何玩家的 .json 文件(实际上很容易获得)并输出玩家拥有的每种符文类型的符文数量。这基本上是我学习 Python(或任何语言)数据的第一周,所以我对此还是很陌生。

我创建的第一本字典是这样的:

rune_set_counts = {}
for i in range(1, 24):
    rune_set_counts[i] = 0

我使范围从 1 开始,因为游戏的 .json 索引符文集使用从 1 到 23 的值。

第二个字典包含 23 个键,每个键都是游戏中特定符文类型的实际名称的字符串。因此,例如,在 rune_set_counts 中,第一个键是 1。在我的第二个字典 rune_set_translated_counts 中,第一个键是对应的名称“能量”。

我想做一个函数,将值从第一个字典转置到第二个字典。如果 rune_set_counts[1] = 5,我想要 rune_set_translated_counts[Energy] = 5。

这是我对功能的尝试:

def convert_to_rune_set(old_dict, new_dict):
    for i in range(len(old_dict)):
        frequency = old_dict[i+1]
        new_dict[i] = frequency

问题是,我试过了,它只是将旧字典中的所有 23 个键值对添加到新字典中,哈哈。我不想要 46 键。我该怎么做?

标签: pythondictionary

解决方案


正如@Tim Roberts 在他的回答中提到的那样,字典没有顺序,你需要一张数字与符文名称的映射。尝试这样的事情。

from random import randint

rune_set_counts = {}
for i in range(1, 24):
    rune_set_counts[i] = randint(0, 10)

print(rune_set_counts)
# prints {1: 0, 2: 0, 3: 6, 4: 5, 5: 0, 6: 4, 7: 3, 8: 0, 9: 2, 10: 7, 11: 6, 12: 7, 13: 7, 14: 4, 15: 4, 16: 6, 17: 4, 18: 0, 19: 4, 20: 10, 21: 0, 22: 5, 23: 2}

rune_name_map = {
    1: "Energy",
    2: "A",
    3: "B",
    # And so on upto 23. You need to create this map hard-coded or read from a json
    23: "V"
}


def convert_to_rune_set(count_map, name_map):
    new_count_map = {}
    for i in range(1, 24):
        new_count_map[name_map[i]] = count_map[i]
        # name_map[i] gives the name mapped to that number
    return new_count_map


new_map = convert_to_rune_set(rune_set_counts, rune_name_map)
print(new_map)
#prints {'Energy': 0, 'A': 0, 'B': 6, 'C': 5, ......., 'V': 2}

推荐阅读