我正在尝试从 dict 创建 csv,但收到以下错误。我最初有键名而不是索引号,但是当我添加多个字典值时会导致错误。
IndexError: tuple index out of range
代码:
#Create dict file to test
userInfoDict = {'orgID': '17', 'firstName': 'TestFirstName', 'lastName': 'TestLastName', 'emailAddress': 'test@test.com',
'phoneNumber': '1234567890', 'isoCountryCode': 'US'}, {'orgID': '27', 'firstName': 'TestFirstName2', 'lastName': 'TestLastName2', 'emailAddress': 'test2@test.com',
'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)