使用键值作为变量的JSON

2024-09-22 10:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我将JSON文件定义为Python程序的配置文件。JSON文件是手工创建的,然后我将使用Python读取JSON并提取数据。 我的观点是多次提到一个键的值。例如:

{
 "seed" : 7,
 "algo1": {
 "random_state": {seed} 
 },
 "algo2": {
 "random_state": {seed} 
 }
}

其思想是使用种子键(本例中为7)中定义的值作为其他键的值。我可以使用这种方法吗?非常感谢


Tags: 文件数据程序json定义配置文件random种子
1条回答
网友
1楼 · 发布于 2024-09-22 10:26:29

根据您希望在这个dict/json中包含多少algos,您可以尝试添加新的algos,如下所示:

cfg = with open('path_to_file/person.json') as json_file:
    data = json.load(json_file)  

cfg["algo1"] = {"random state": cfg["seed"]}

cfg["algo2"] = {"random state": cfg["seed"]}

相关问题 更多 >