Чтобы вставить новую пару key
- value
в ваш словарь, вам необходимо создать метод для получения данных от пользователя.
В __init__
вы можете объявить пустой словарь, а затем в insert
метод, вы можете получить новую запись от пользователя.
Более того, для отображения текущих элементов словаря вы можете создать отдельный метод с именем display
.
json
встроенный может напрямую записывать и читать данные типа словаря из файла json. Вы можете прочитать о json
из официальной документации на json.
import json
import os
class Mydictionary:
def __init__(self, file_name):
self.json_file = file_name
if os.path.exists(file_name):
with open(self.json_file, "r") as json_output:
self.data = json.load(json_output)
else:
self.data = {}
def insert(self):
user_key = input("Please input word: ")
user_value = input("Please input meaning of the word: ")
self.data[user_key] = user_value
with open(self.json_file, "w") as json_output:
json.dump(self.data, json_output)
def display(self):
if os.path.exists(self.json_file):
with open(self.json_file, "r") as json_output:
print(json.load(json_output))
else:
print("{} is not created yet".format(self.json_file))
Mydic=Mydictionary("data.json")
Mydic.display()
Mydic.insert()
Mydic.insert()
Mydic.display()
Вывод:
data.json is not created yet
Please input word: rain
Please input meaning of the word: water droplets falling from the clouds
Please input word: fire
Please input meaning of the word: Fire is a chemical reaction that releases light and heat
{'rain': 'water droplets falling from the clouds', 'fire': 'Fire is a chemical reaction that releases light and heat'}
Отказ от ответственности : Это это просто концепция объявления и использования классов и методов. Вы можете импровизировать этот подход.