如何在字典中对用户删除的内容的频率进行编码?

2024-04-19 16:48:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点问题。我想查看一个用户从一个键中删除一个值的次数,即使用户退出程序,它仍然会保留这个数字。因此,在将来,如果用户想再次删除任何值,它将使用现有的数字和从那里添加。你知道吗

编辑:只是添加。所有dict都将存储在.txt文件中

dict= {}  #start off with an empty list

key_search = ("Enter to find a key")

if options_choose == 2:
    c = input('Which value would you like to change? ')
    c = change.lower()

    if change in list_of_value:
        loc = list_of_value.index(c)
        list_of_value.remove(c)
        correction = input("Enter correction: ")
        correction = correction.lower()
        print(f"value(s) found relating to the key '{key_search}' are:")
        list_of_value.insert(loc, correction)
        list_of_value = dict[key_search]

        for key, value in enumerate(list_of_value, 1):
            print(f"{key}.) {value}")
        else:
            print('Entry invalid')

Tags: oftokey用户inputsearchifvalue
1条回答
网友
1楼 · 发布于 2024-04-19 16:48:24

正如你在下面的屏幕截图中看到的那样,我已经退出并用相同的计数器重新进入程序。你知道吗

enter image description here

您可以调整它以适应您的程序的功能。因为您提供的代码似乎不完整,所以我用一个字典修改的示例来代替它,以展示如何在程序终止后存储和读取值。你知道吗

你必须有一个文件夹测试.py以及修改.value.txt在里面。在文本文件中写入“0”。你知道吗

ex_dict= {'example_entry':1}

#Read in the value stored into the text file.
with open('modification_value.txt','r') as file:
    counter = int(file.readline()) #counter value imported from file.

print('Counter: ', counter)

modify_dict = True #boolean to check when user wants to stop making changes


while modify_dict == True:

    for key in ex_dict:
        dict_key = key
    new_value = input('Enter value for new key.\n')
    ex_dict[dict_key] = new_value
    counter+=1

    print('New dictionary: ', ex_dict, '\n')

    response = input("Do you still want to modify Y/N?\n")
    if (response =='Y'):
        continue
    elif(response =='N'):
        modify_dict=False

#Write the value of the counter recorded by the program to the text file so the program can access it when it is run again after termination.
with open('modification_value.txt','w+') as file:
    file.write(str(counter))

相关问题 更多 >