如何将JSON字典转移到给定条件的多个文件中



我正在尝试从用户输入为每个学生创建一个单独的JSON文件。

目前,我只能将所有信息转入一个文件中,但是我需要根据用户输入的名称在单独的文件中词典。

我也每次用户输入时都试图更新字典

import json
def get_input():
#user input to record in log
    name = input("Name:")
    d = {} #my dictionary
    d['date'] = input('Enter a date in YYYY-MM-DD format:')
    d['hours'] = input("Hours:")
    return(name,d)
out = {}
while True:
    exit = input('Do you want to add another input (y/n)?')
if exit.lower() == 'n':
    break
else:
    name, d = get_input()
    out[name] = d
#dump into separate file according to name from user input
if name == 'Jessica':
    with open('jessica.json','a') as j:
       json.dump(out, j, indent= 2)
elif: name == 'Wendy':
    with open('wendy.json','a') as w:
       json.dump(out, w, indent= 2)
else:
    with open('tat.json','a') as t:
       json.dump(out, t, indent= 2)

代码的问题是,每当变量名称的值都被输入的姓氏覆盖时。尝试为每个输入的每个迭代保存JSON文件。但是更改字典的名称是因为内容均匀。

import json
def get_input():
#user input to record in log
    name = input("Name:")
    d = {} #my dictionary
    d['date'] = input('Enter a date in YYYY-MM-DD format:')
    d['hours'] = input("Hours:")
    return name,d
out = {}
name=''
d=''
while True:
    exit = input('Do you want to add another input (y/n)?')
    print(exit)
    if exit.lower()=='n':
        break
    else:
        name, d = get_input()
        out[name] = d
        with open(name + '.json','a') as j:
            json.dump(out, j, indent= 2)
        out={}
#dump into separate file according to name from user input
if name == 'Jessica':
    with open('jessica.json','a') as j:
       json.dump(out, j, indent= 2)
else:
    if name == 'Wendy':
        with open('wendy.json','a') as w:
            json.dump(out, w, indent= 2)
    else:
        with open('tat.json','a') as t:
            json.dump(out, t, indent= 2)
    enter code here

如果我正确理解您的问题,您想为每个人创建一个新的JSON文件,并且该人有自己的相应词典。

一种解决方案是创建字典词典。

out = {
    'jessica':{'date': x, 'hours': y},
    'wendy':{'date': x2, 'hours': y2}
}

,然后在 out 字典上循环。

for name, dictionary in out.items():
    with open(name,'a') as j:
       json.dump(dictionary , j, indent= 2)

相关内容

  • 没有找到相关文章

最新更新