[英]Not sure why I am getting this error, I have an idea but am not sure how to fix it
[英]I am getting a KeyError an am not sure how to fix it
我已經寫出了我的代碼,當我運行它時,我得到一個 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'
我的代碼:
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)
我已經查找了如何修復它,只是不確定是否執行了 try-except 函數。 如果有人能幫我解決這個問題,那就太棒了..
這是給定文件中的內容:
'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()
只產生達到較短迭代長度的結果:
print(list(zip([1,2],[1,2,3,4,5,6]))) # [(1, 1), (2, 2)]
您的源數據以某種方式至少有一行元素較少,這就是為什么您的一個字典沒有“出生日期”鍵(最后一個)的原因。
你可以防范它:
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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.