我想制作一个从文本(dictionary)读取信息的程序。如果key不存在,则程序应添加此key,并且还必须逐行将keyvalue添加到文本文件中。我做了些什么,但是在阅读部分时,有问题说列表索引超出范围。有人可以帮忙吗?

with open('text.txt','r') as file:
    x={}
    for line in file:
        key = line.rstrip().split(':')[0]
        keyvalue = line.rstrip().split(':')[1]
        x[key]=keyvalue
while True:
    name = input('whose hobby you wanna learn?:')
    if name in x:
        print('Name found')
        print("%s's hobby is %s" %(name,x[name]))
    else:
        print('i do not know',name)
        answer = input('do you wanna add this person?(yes or no)')
        if answer == ('yes'):
            new_user= input('type the name of new person:')
            new_user_hobby = input('type the hobby of that person:')
            x[new_user] = new_user_hobby
            with open('text.txt','a') as file:
                file.write('\n')
                file.write(new_user)
                file.write(':')
                file.write(new_user_hobby)
            print('person created successfully!')
分析解答

使用JSON。

文件data.json

{
    "key1": "value1",
    "key2": "value2"
}

文件main.py

import json

with open("data.json", "r") as jsonfile:
    data = json.load(jsonfile)
    key = input("enter key: ")
    if key in data:
        print("key %s has value %s" % (key, data[key]))
    else:        
        add = input("key %s was not found in the data; do you want to add it ? " % key)
        if add:
            value = input("enter value for key %s : " % key)
            data[key] = value
    jsonfile.close()
    with open("data.json", "w") as jsonfile:
        json.dump(jsonfile, data)

如果运行它,请输入key3,然后输入yes,然后输入value3,然后data.json文件将如下所示:

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}