Good day. There is a test1 file with its contents:

!Сколько будет 2 + 2? -5 -6 +4 -3 # !Сколько будет 2 + 3? -5 +6 -4 -3 # !Кто такой Александ Македонский? -гаплит +величайший завоеватель всех времен -Цезарь -Сын Зевса 

Is my logic correct? If in the file the mark! Is the question - Not the correct answer + the correct answer "#" - a new question, the list with answers is erased

File reading script:

 import json with open("test1", "r", encoding="utf-8") as file: with open("test.json", "w", encoding="utf-8") as f: question_test = dict() answer_list = list() for line in file.readlines(): if line[0] == "!": qwestion = line question_test[qwestion] = [] elif line[0] == "-": false_answer = line answer_list.append(false_answer) negative_answer = line elif line[0] == "+": tru_anser = line answer_list.append(tru_anser) elif line[0] == "#": del answer_list[:] question_test[qwestion] = answer_list json.dump(question_test, f, ensure_ascii=False, indent=2) 

The problem itself is that when saving to json, I get the following result:

 { "!Кто такой Александ Македонский?\n": [ "-гаплит\n", "+величайший завоеватель всех времен\n", "-Цезарь\n", "-Сын Зевса" ], "!Сколько будет 2 + 2?\n": [ "-гаплит\n", "+величайший завоеватель всех времен\n", "-Цезарь\n", "-Сын Зевса" ], "!Сколько будет 2 + 3?\n": [ "-гаплит\n", "+величайший завоеватель всех времен\n", "-Цезарь\n", "-Сын Зевса" ] } 

ie, the key is created and the values ​​of only the last question in the file. I need a kick from more experienced colleagues)). thank

  • How much is 2 + 3? Check the correct answer ... - Lex Hobbit
  • Thank you for your comment. - Peter Kuznetsov

1 answer 1

For example, such an algorithm (it is always easier to write from scratch in such cases than to deal with someone else’s code):

 from collections import defaultdict question_test = defaultdict(list) with open('test', mode='r', encoding='utf-8') as f: # Защита от дурака которая проверяет чтобы в файле сначала была # строка с вопросом question = None for line in f: # Удаление ' ', '\n', '\t', '\r' из начала и конца строки line = line.strip() # Защита от дурака которая проверяет чтобы строка не была пустой if not line: continue type_line = line[0] if type_line == '!': question = line[1:] continue if type_line not in '-+': continue if not question: continue question_test[question].append(line) import json json_data = json.dumps(question_test, ensure_ascii=False, indent=4) print(json_data) 

If the order of questions is important, then you need to use OrderedDict :

 from collections import OrderedDict question_test = OrderedDict() with open('test', mode='r', encoding='utf-8') as f: # Защита от дурака которая проверяет чтобы в файле сначала была # строка с вопросом question = None for line in f: # Удаление ' ', '\n', '\t', '\r' из начала и конца строки line = line.strip() # Защита от дурака которая проверяет чтобы строка не была пустой if not line: continue type_line = line[0] if type_line == '!': question = line[1:] continue if type_line not in '-+': continue if not question: continue if question not in question_test: question_test[question] = list() question_test[question].append(line) import json json_data = json.dumps(question_test, ensure_ascii=False, indent=4) print(json_data) 

Console:

 { "Сколько будет 2 + 2?": [ "-5", "-6", "+4", "-3" ], "Сколько будет 2 + 3?": [ "-5", "+6", "-4", "-3" ], "Кто такой Александ Македонский?": [ "-гаплит", "+величайший завоеватель всех времен", "-Цезарь", "-Сын Зевса" ] }