Reputation: 7
I'm trying to append key's to other key's based on their name, but when i go through my if row.has_key(ft_test) statement, if the row doesn't have the value from ft_test, it doesn't append AND it goes on to the next if statement. I'd like for the code to return to the for ft in fieldMap.keys() line. Is there anyway to do this with an else statement or am i hopeless?
#!/usr/bin/env python
import sys
import csv
import glob
fieldMap = {'zipcode':['Zip5', 'zip9','zipcode','ZIP','zip_code','zip','ZIPCODE'],
'firstname':['firstname','FIRSTNAME'],and insert
'lastname':['lastname','LASTNAME'],
'cust_no':['cust_no','CUST_NO'],
'user_name':['user_name','USER_NAME'],# the keys here are ft
'status':['status','STATUS'],# status must be filled
'cancel_date':['cancel_date','CANCEL_DATE'],
'reject_date':['REJECT_DATE','reject_date'],
'streetaddr':['streetaddr','address2','STREETADDR','ADRESS2','ADDRESS','address'],
'streetno':['streetno','STREETNO'],
'streetnm':['streetnm','STREETNM'],
'suffix':['suffix','SUFFIX'],
'city':['city','CITY'],
'state':['state','STATE'],
'phone_home':['phone_home','PHONE_HOME'],
'email':['email','EMAIL']
}
def readFile(fn,ofp):
count = 0
CSVreader = csv.DictReader(open(fn,'rb'), dialect='excel', delimiter=',')
for row in CSVreader:
count+= 1
if count == 1:
hdrlist = []
for ft in fieldMap.keys():
hdrlen = len(hdrlist)
for ft_test in fieldMap[ft]:
if row.has_key(ft_test):
hdrlist.append(ft_test)
if hdrlen != len(hdrlist)+1:
print "Cannot find a key for %s" % ft
sys.exit(1)
Upvotes: 0
Views: 157
Reputation:
Add the break
keyword:
hdrlen = len(hdrlist) # hdrlen equals the number of headers in header list
for ft_test in fieldMap[ft]:# ft_test = values of keys in field map
if row.has_key(ft_test): # if a row has a key from the values from fieldMap # why does it stop after testing only one key??????????????
hdrlist.append(ft_test)
break
When the if
case is True
, it will break
out of the inner for-loop
.
Upvotes: 1