Reputation: 179
I'm trying to create a csv from a dict, but I'm receiving the following error. I originally had key names instead of index numbers but it caused an error when I added multiple dictionary values.
IndexError: tuple index out of range
Code:
#Create dict file to test
userInfoDict = {'orgID': '17', 'firstName': 'TestFirstName', 'lastName': 'TestLastName', 'emailAddress': '[email protected]',
'phoneNumber': '1234567890', 'isoCountryCode': 'US'}, {'orgID': '27', 'firstName': 'TestFirstName2', 'lastName': 'TestLastName2', 'emailAddress': '[email protected]',
'phoneNumber': '5384537645', 'isoCountryCode': 'US'}
def create_csv(userInfoDict):
import csv
userInfo = open('userInfo.csv', 'w')
for key in userInfoDict:
if len(userInfoDict[0]) == 0:
print('Not a valid user: No orgID')
return None
elif len(userInfoDict[1]) == 0:
print('Not a valid user: No First Name')
return None
elif len(userInfoDict[3]) == 0 and len(userInfoDict[4]) == 0:
print('Not a valid user: No Email or Phone')
return None
else:
writer = csv.DictWriter(userInfo, fieldnames=userInfoDict.keys(), delimiter=',')
#writer.writeheader() # If you want to add header
writer.writerow(userInfoDict)
return
create_csv(userInfoDict)
Upvotes: 0
Views: 604
Reputation: 9133
That is because your 'userInfoDict' is tuple with length of two.
len(userInfoDict)
2
But you seem to trying to access 'userInfoDict[3]' and userInfoDict[4] in your code which isn't there.
See below
userInfoDict[0]
{'emailAddress': '[email protected]',
'firstName': 'TestFirstName',
'isoCountryCode': 'US',
'lastName': 'TestLastName',
'orgID': '17',
'phoneNumber': '1234567890'}
and
userInfoDict[1]
{'emailAddress': '[email protected]',
'firstName': 'TestFirstName2',
'isoCountryCode': 'US',
'lastName': 'TestLastName2',
'orgID': '27',
'phoneNumber': '5384537645'}
So any index beyond 1 will give you out of index error
userInfoDict[2]
IndexError: tuple index out of range
Please check your 'userInfoDict' that is not a dict, it is a tuple.
Upvotes: 0
Reputation: 586
The userInfoDict
you provided is a tuple
of two dicts
, equivalent to:
userInfoDict = ({'orgID': '17', 'firstName': 'TestFirstName', 'lastName': 'TestLastName', 'emailAddress': '[email protected]','phoneNumber': '1234567890', 'isoCountryCode': 'US'},
{'orgID': '27', 'firstName': 'TestFirstName2', 'lastName': 'TestLastName2', 'emailAddress': '[email protected]', 'phoneNumber': '5384537645', 'isoCountryCode': 'US'}
)
Yet you are trying to calculate len(userInfoDict[3])
. It has no element with index 3, only with indices 0 and 1.
Upvotes: 1