سؤال

I have the following code:

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['Name'] == name:
                print record


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

When I use this to try and locate a record, I get the following output:

Enter name: Daniel Ghi
{'Home Phone No.': 'Example', 'Mobile Phone No.': 'Example', 'Name': 'Daniel Ghi
', 'Address': 'Example'}
Traceback (most recent call last):
  File "address.py", line 35, in <module>
    search_for_person(name)
  File "address.py", line 18, in search_for_person
    if record['Name'] == name:
KeyError: 'Name'

As you can see, this does actually print out the correct data, but it still comes up with a KeyError, and I'm not sure why. Can anyone enlighten me?

هل كانت مفيدة؟

المحلول

It prints out the correct data, then keeps running and raises a KeyError on later data.

Most likely your file ends with a ------ string, so your split produces a list with an empty string at the very end, which then produces an empty dict, which naturally doesn't have any keys in it.

Easy fix is to just skip the data if it's empty, or only whitespace, or if record is empty. More robust fix is to avoid using [] syntax when you can't be sure what keys each dict actually has; use record.get('Name', None) instead.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top