我想使用数据帧(取自csv文件)中的值和代码中定义的值创建一个字典。然后需要将其写入json文件。下面是我的代码和预期的输出。我想更新与保存现有值的键相关的值。
import json
import os.path
import pandas as pd
df = pd.read_csv('country.csv')
diction = {}
for index, row in df.iterrows():
a = "country_details"
u = "global"
g = str(row['name'])
h = str(row['country_code'])
i = str(row['region'])
diction.update({
"initial_configurations":
{
g: [
[f"{a}", f"{g}"],
[f"t_s{u}", f"{h}"]]
},
"final_configurations":
{
g: [
[f"{a}", f"{g}"],
[f"t_s{u}", f"{h}"]]
},
})
with open('web.json', 'a', encoding='utf-8') as file:
# for row in df:
json.dump(diction, file, ensure_ascii=False)
链接到csv文件- https://drive.google.com/file/d/10AHu-njt2AIDFe3j5BPVJcENKqh_3Uck/view?usp=share_link
我正在走下坡路
{"initial_configurations": {"Qatar": [["country_details", "Qatar"], ["t_sglobal", "QA"]]}, "final_configurations": {"Qatar": [["country_details", "Qatar"], ["t_sglobal", "QA"]]}}
但是我想要得到下面,不仅仅是最后一个值Quatar,我需要在日期框架中的'name'下有其他值,而不覆盖
{"initial_configurations":{"Australia": [["country_details", "Australia"], ["t_sglobal", "AU"]],[["country_details", "Bangladesh"], ["t_sglobal", "BD"]]....},
"final_configurations": {"Australia": [["country_details", "Australia"], ["t_sglobal", "AU"]],[["country_details", "Bangladesh"], ["t_sglobal", "BD"]]...}}
每次迭代都覆盖initial_configurations
和final_configurations
键,您需要为这些键附加值
diction = {'initial_configurations': dict(), 'final_configurations': dict()}
for index, row in df.iterrows():
a = "country_details"
u = "global"
g = str(row['name'])
h = str(row['country_code'])
diction['initial_configurations'].update({g: [[f"{a}", f"{g}"], [f"t_s{u}", f"{h}"]]})
diction['final_configurations'].update({g: [[f"{a}", f"{g}"], [f"t_s{u}", f"{h}"]]})
web.json
:
{"initial_configurations": {"Australia": [["country_details", "Australia"], ["t_sglobal", "AU"]], "Bangladesh": [["country_details", "Bangladesh"], ["t_sglobal", "BD"]], "India": [["country_details", "India"], ["t_sglobal", "IND"]], "New Zealand": [["country_details", "New Zealand"], ["t_sglobal", "NZ"]], "Norway": [["country_details", "Norway"], ["t_sglobal", "NO"]], "Poland": [["country_details", "Poland"], ["t_sglobal", "PL"]], "Qatar": [["country_details", "Qatar"], ["t_sglobal", "QA"]]},
"final_configurations": {"Australia": [["country_details", "Australia"], ["t_sglobal", "AU"]], "Bangladesh": [["country_details", "Bangladesh"], ["t_sglobal", "BD"]], "India": [["country_details", "India"], ["t_sglobal", "IND"]], "New Zealand": [["country_details", "New Zealand"], ["t_sglobal", "NZ"]], "Norway": [["country_details", "Norway"], ["t_sglobal", "NO"]], "Poland": [["country_details", "Poland"], ["t_sglobal", "PL"]], "Qatar": [["country_details", "Qatar"], ["t_sglobal", "QA"]]}}