Python 我从字典中删除了数据并编写了字典';将数据转换为文本文件并获取密钥错误?
我有一个如下所示的文本文件: myFiles.txtPython 我从字典中删除了数据并编写了字典';将数据转换为文本文件并获取密钥错误?,python,dictionary,Python,Dictionary,我有一个如下所示的文本文件: myFiles.txt Dell 2015 A14523 Sam Sony 2014 A74256 John Acer 2018 A45656 Mark Sony 2007 S12345 James 我想在输入索引时删除数据,因此,我将文本文件转换为字典。通过这种方式,我得到了文本文件的索引。但当我从字典中删除任何数据并将其余数据写入文本文件时,就会出现一个关键错误。 因为当我从字典中删除数据时,索引保持不变
Dell 2015 A14523 Sam
Sony 2014 A74256 John
Acer 2018 A45656 Mark
Sony 2007 S12345 James
我想在输入索引时删除数据,因此,我将文本文件转换为字典。通过这种方式,我得到了文本文件的索引。但当我从字典中删除任何数据并将其余数据写入文本文件时,就会出现一个关键错误。
因为当我从字典中删除数据时,索引保持不变
例如:
我已经为不同的键创建了4行,即1、2、3和4
当我从索引2中删除数据时,字典索引保持不变,我留下了1、3和4,当我将数据重写到文本文件时,它将给出键错误。
如何从文本文件中删除数据。
我是python新手。请帮助我解决它
def deleteFunction(self):
ownerListDic = {}
num = 1
with open("myFiles.txt", "r") as oy:
for line in oy:
li = line.strip().split()
ownerListDic[num] = {"name": li[0], "purchase": li[
1], "bluePlate": li[2], "owner": li[3]}
num += 1
# enter the record id to delete from the text file
indexId = int(input("Enter record ID: "))
if indexId in ownerListDic:
# prompting to confirm the user you are going to delete
# this data
print(("You arev about to delete " + ''.join(ownerListDic[indexId]['name'] +
" " + ownerListDic[indexId]['purchase'] + " " + ownerListDic[indexId]["bluePlate"] + " " + ownerListDic[indexId]['owner'])) + " .")
# ask user to delete the data
delete = input(
"Do you wish to delete this record (Y/N): ").upper()
# if yes then data will delete
if delete == "Y":
ownerListDic.pop(indexId, None)
num=1
with open("myFiles.txt", 'w') as log:
for dataValue in ownerListDic.values():
log.write(ownerListDic[num]['name'] +
"\t" + ownerListDic[num]['purchase'] + "\t" + ownerListDic[num]["bluePlate"] + "\t" + ownerListDic[num]['owner'] + "\n")
num += 1
# after deletion this message will print
print("Record deleted.")
我想您要查找的是ownerListDic.items()中的num、dataValue的
:
。这样,您将编写字典的实际键,而不是索引(在删除任何内容之前,索引是相同的,但现在不再是)。我不确定你是否想把钥匙保存在文件中,这样你就可以在以后的运行中取回相同的钥匙,但这并不难。很好,谢谢,先生,谢谢你,做得很好,现在我想我浪费了一整晚的时间来试着找到正确答案非常感谢,先生