简体   繁体   中英

I am getting a KeyError an am not sure how to fix it

I have written out my code and when I run it, I get a KeyError:

Traceback (most recent call last):
  File "C:/Users/sagar/Desktop/Sagar CS131B Files/convert_to_fixed.py", line 21, in <module>
    birthdate = sample['Birthdate']
KeyError: 'Birthdate'

my code:

inputFile = 'raw.data.py'

data = list()
columns = ['First name','Last name','Telephone','Address','City','State','Birthdate']
for line in open(inputFile):
    # Assuming comments in the text file as '#'
    if line.startswith('#'): continue
    row = line.strip().split(':')
    data.append(dict(zip(columns, row)))
#print(data)

formatted_data = list()
for sample in data:
    birthdate = sample['Birthdate']
    mm,dd,yy = birthdate.split('/')
    if len(yy)==2:
        yy = '19' + yy
        birthdate = '/'.join([mm,dd,yy])
        sample['Birthdate'] = birthdate
    modified_row = ':'.join(
        [sample['Last name'], sample['First name'],
        sample['Telephone'], sample['Address'],
        sample['City'], sample['State'], sample['Birthdate']])
    formatted_data.append(modified_row + '\n')


with open('fixed.data','w') as f:
    f.writelines(formatted_data)

I have looked up how to fix it, just not sure on the execution of a try-except function. If someone could help me out with this that would be amazing..

This is what is inside the file given:

'Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:6/23/1923',
'Ephram:Hardy:293-259-5395:235 Carlton Lane:Joliet:IL:8/12/1920',
'Fred:Fardbarkle:674-843-1385:20 Parak Lane:DeLuth:MN:4/12/23',
'Igor:Chevsky:385-375-8395:3567 Populus Place:Caldwell:NJ:6/18/68',
'James:Ikeda:834-938-8376:23445 Aster Ave.:Allentown:NJ:12/1/1938',
'Jennifer:Cowan:548-834-2348:408 Laurel Ave.:Kingsville:TX:10/1/35',
'Jesse:Neal:408-233-8971:45 Rose Terrace:San Francisco:CA:2/3/2001',
'Jon:DeLoach:408-253-3122:123 Park St.:San Jose:CA:7/25/53',
'Jose:Santiago:385-898-8357:38 Fife Way:Abilene:TX:1/5/58',
'Karen:Evich:284-758-2867:23 Edgecliff Place:Lincoln:NB:11/3/35',
'Lesley:Kirstin:408-456-1234:4 Harvard Square:Boston:MA:4/22/2001',
'Lori:Gortz:327-832-5728:3465 Mirlo Street:Peabody:MA:10/2/65',
'Norma:Corder:397-857-2735:74 Pine Street:Dearborn:MI:3/28/45',
'Paco:Gutierrez:835-365-1284:454 Easy Street:Decatur:IL:2/28/53',
'Popeye:Sailor:156-454-3322:945 Bluto Street:Anywhere:USA:3/19/35',
'Sir:Lancelot:837-835-8257:474 Camelot Boulevard:Bath:WY:5/13/69',
'Steve:Blenheim:238-923-7366:95 Latham Lane:Easton:PA:11/12/1956',
'Tommy:Savage:408-724-0140:1222 Oxbow Court:Sunnyvale:CA:5/19/66',
'Vinh:Tranh:438-910-7449:8235 Maple Street:Wilmington:VM:9/23/63',
'William:Kopf:846-836-2837:6937 Ware Road:Milton:PA:9/21/46',
'Yukio:Takeshida:387-827-1095:13 Uno Lane:Ashville:NC:7/1/29',
'Zippy:Pinhead:834-823-8319:2356 Bizarro Ave.:Farmount:IL:1/1/67',
'Andy:Warhol:212-321-7654:231 East 47th Street:New York City:NY:8/6/1928'

zip() only produces results up to the shorter iterables length:

print(list(zip([1,2],[1,2,3,4,5,6])))     #  [(1, 1), (2, 2)]

Your source data somehow at least one line with less elements in it that is why one of your dicts does not have the 'Birthdate' key (the last one).

You can guard against it:

data = list() 
columns = ['First name', 'Last name', 'Telephone', 
           'Address', 'City', 'State', 'Birthdate'] 

# use a context manager for file open
with open(inputFile) as f: 
    for line in f:
        # Assuming comments in the text file as '#'
        if line.startswith('#'): 
            continue

        # ignore empty lines (you can combine with above)
        if not line.strip():
            continue

        row = line.strip().split(':')
        # raise exception if not enough data found
        if len(row) != len(columns):
            raise AttributeError("Not enough datapoints in line: ", line)

        data.append(dict(zip(columns, row)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM