import ast # needed to read text as a dictionary
import operator # needed to find term with maximum value
def define_words():
final_dict={}
with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt','r', encoding = "utf-8") as dic:
dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary
print('the start length was: ', len(dante_dict)) # start length of source dictionary
key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0]
print('The next word to define is ', key_to_find) # show which word needs defining
definition = input('Definition ? : ') # prompt for definition
for key in dante_dict.keys():
if key == key_to_find:
final_dict.update({key_to_find:definition})
dante_dict.pop(key_to_find)
print('the end length is : ' ,len(dante_dict))
print(dante_dict) # print source dictionary, modified
print(final_dict) # print dictionary with newly defined entry
with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt', 'w', encoding = 'utf-8') as outfile:
outfile.write(str(dante_dict)) # writes source dictionary minus newly-defined term
with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'w', encoding = 'utf-8') as finalfile:
finalfile.write(str(final_dict))
我很抱歉重新发布类似的问题以回应我所获得的帮助。不知道如何添加修改。我仍然有这个问题。我的最终字典每次都会被覆盖,而不是附加新定义的术语,所以字典只包含最后一个键:值对。我认为通过使用 dict_name[key] = value,新条目将被附加,而其他条目保持不变。帮助表示赞赏