代码之家  ›  专栏  ›  技术社区  ›  Penny Pang

如何在给定条件下将json字典转储到多个文件中

  •  0
  • Penny Pang  · 技术社区  · 7 年前

    我试图通过用户输入为每个学生创建一个单独的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)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   raultedesco    7 年前

    代码的问题是,每次变量名的值都会被输入的姓氏覆盖。尝试为每个输入迭代保存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
    
        2
  •  0
  •   Thomas S.    7 年前

    如果我正确理解了您的问题,那么您希望为每个人创建一个新的json文件,并且每个人都有自己相应的字典。

    一个解决方案是创建一个字典字典。

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

    然后在 出来 词典

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