gpt4 book ai didi

python - 通过字典名称从不同的字典中获取信息

转载 作者:太空宇宙 更新时间:2023-11-04 09:08:03 26 4
gpt4 key购买 nike

我有一个数据/character_data.py:

CHARACTER_A = { 1: {"level": 1, "name":"Ann", "skill_level" : 1},
2: {"level": 2, "name":"Tom", "skill_level" : 1}}
CHARACTER_B = { 1: {"level": 1, "name":"Kai", "skill_level" : 1},
2: {"level": 2, "name":"Mel", "skill_level" : 1}}

在 main.py 中,我可以这样做:

from data import character_data as character_data
print character_data.CHARACTER_A[1]["name"]
>>> output: Ann
print character_data.CHARACTER_B[2]["name"]
>>> output: Mel

我如何实现这一目标?

from data import character_data as character_data
character_type = "CHARACTER_A"
character_id = 1
print character_data.character_type[character_id]["name"]
>>> correct output should be: Ann

尝试将 character_type 用作“CHARACTER_A”时出现 AttributeError。

最佳答案

这个怎么样

In [38]: from data import character_data as character_data

In [39]: character_type = "CHARACTER_A"

In [40]: character_id = 1

In [41]: getattr(character_data, character_type)[character_id]["name"]
Out[41]: 'Ann'

关于python - 通过字典名称从不同的字典中获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18170997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com