【问题标题】:KeyError when trying to write dict to file [Python]尝试将字典写入文件时出现 KeyError [Python]
【发布时间】:2013-10-27 22:07:12
【问题描述】:

代码:

import re


def add_details(details_dict, file_mode):
    with open("address.txt", file_mode) as book:
        book.write("Name: {}\n".format(details_dict['Name']))
        book.write("Address: {}\n".format(details_dict['Address']))
        book.write("Home Phone No.: {}\n".format(details_dict['Home Phone No.']))
        book.write("Mobile Phone No.: {}".format(details_dict['Mobile Phone No.']))
        book.write("\n---------------\n")



def delete_person(name):
    with open("address.txt", "r+") as book:
        records = re.split("[-]+", book.read(), re.M)
        for data in records:
            record = get_record(data)
            if record.get('Name', None) != name:
                add_details(record, "w")


def get_record(string):
    return dict(re.findall("^(.*): (.*)$", string, re.M))


def print_record(record):
    print "\n"
    print "Name: {}".format(record['Name'])
    print "Address: {}".format(record['Address'])
    print "Home Phone No.: {}".format(record['Home Phone No.'])
    print "Mobile Phone No.: {}".format(record['Mobile Phone No.'])


def search_for_person(name):
    with open("address.txt", "r") as book:
        records = re.split("[-]+", book.read(), re.M)
        for data in records:
            record = get_record(data)
            if record.get('Name', None) == name:
                print_record(record)


choice = raw_input("Add a new person (1), delete a person(2), or search for a person(3)?\n")
if choice == "1":
    details = {'Name':"", 'Address':"", 'Home Phone No.':"", 'Mobile Phone No.':""}
    details['Name'] = raw_input("Enter name of contact: ")
    details['Address'] = raw_input("Enter address of contact: ")
    details['Home Phone No.'] = raw_input("Enter Home Telephone No. of contact: ")
    details['Mobile Phone No.'] = raw_input("Enter Mobile Telephone No. of contact: ")

    add_details(details, "a")

elif choice == "2":
    name = raw_input("Enter name to delete: ")
    delete_person(name)

elif choice == "3":
    name = raw_input("Enter name: ")
    print search_for_person(name)

基本上,每当我尝试使用 delete_person() 方法删除一个人时,我都会得到以下回溯:

Traceback (most recent call last):
  File "address.py", line 56, in <module>
    delete_person(name)
  File "address.py", line 19, in delete_person
    add_details(record, "w")
  File "address.py", line 6, in add_details
    book.write("Name: {}\n".format(details_dict['Name']))
KeyError: 'Name'

但是,除了该方法之外,一切都可以正常工作。考虑到我已经以完全相同的方式设置字典,我不应该得到错误,但无论如何我是。对此有什么帮助吗?如果需要,这是文件的布局:

Name: test
Address: testaddress
Home Phone No.: 2313123121233
Mobile Phone No.: 423423423432
---------------
Name: test2
Address: testaddress2
Home Phone No.: 342353454345
Mobile Phone No.: 231231391
---------------

【问题讨论】:

  • details_dict 在抛出 KeyError 的行之前是什么样子的?

标签: python dictionary keyerror


【解决方案1】:

您总是在录制后添加-------;这会导致读取 empty 记录,因为在最后一行之后只有空格:

>>> record='''\
... Name: test
... Address: testaddress
... Home Phone No.: 2313123121233
... Mobile Phone No.: 423423423432
... ---------------
... '''
>>> import re
>>> re.split("[-]+", record, re.M)
['Name: test\nAddress: testaddress\nHome Phone No.: 2313123121233\nMobile Phone No.: 423423423432\n', '\n']

注意最后的'\n' 条目。这会导致没有'Name' 键的空字典:

>>> dict(re.findall("^(.*): (.*)$", '\n', re.M))
{}

测试空字典:

record = get_record(data)
if record and record.get('Name', None) == name:

【讨论】:

  • 嗯,有道理...关于如何解决这个问题的任何想法,然后?我想将--------- 保留在那里以用于分隔目的,以保持文件可读。
  • @dantdj:看答案的最后几句;通过使用if record 测试跳过空记录(并且空容器在布尔上下文中始终为False)。
  • 啊,哎呀,我的坏...眼睛累了。非常感谢,伙计!现在都在工作。 :)
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多