Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to loop on the dictionary I am using python 3 latest version

string indices must be integers when dictionary in the loop



data analysis









from datetime import datetime as dt

# Takes a date as a string, and returns a Python datetime object.

# If there is no date given, returns None

def parse_date(date):

if date == '':

return None

else:

return dt.strptime(date, '%Y-%m-%d')

# Takes a string which is either an empty string or represents an integer,

# and returns an int or None.

def parse_maybe_int(i):

if i == '':

return None

else:

return int(i)

# Clean up the data types in the enrollments table

for enrollment in enrollments:

enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])

enrollment['days_to_cancel'] = parse_maybe_int(enrollment['days_to_cancel'])

enrollment['is_canceled'] = enrollment['is_canceled'] == 'True'

enrollment['is_udacity'] = enrollment['is_udacity'] == 'True'

enrollment['join_date'] = parse_date(enrollment['join_date'])

enrollments[0]



here is error



TypeError Traceback (most recent call last)

<ipython-input-3-118808c6a8e0> in <module>

19 # Clean up the data types in the enrollments table

20 for enrollment in enrollments:

---> 21 enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])

22 enrollment['days_to_cancel'] = parse_maybe_int(enrollment['days_to_cancel'])

23 enrollment['is_canceled'] = enrollment['is_canceled'] == 'True'

TypeError: string indices must be integers


What I have tried:

looping on the dictionary . update value gives me the error
TypeError: string indices must be integers
Posted
Updated 27-Nov-19 6:43am
Comments
Patrice T 27-Nov-19 3:37am    
Indentation is part f the meaning of code in Python.
We can't guess nothing without it.

1 solution

The error message clearly says that enrollment is a string, not a dictionary.

You need to look at where your enrollments sequence is coming from to work out why it's not the type you think it is.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900