Python - index out of range error -


i have example text python working on.

  afghanistan:32738376   akrotiri:15700   albania:3619778   algeria:33769669   american samoa:57496   andorra:72413   angola:12531357   anguilla:14108   antigua , barbuda:69842   argentina:40677348   armenia:2968586   aruba:101541   australia:20600856   austria:8205533   azerbaijan:8177717 

i have code make dictionary using country names , population.

 dct = {}   line in infile:     line = line.strip()     words = line.split(":")     countryname = words[0]      population = int(words[1])     dct[countryname] = population 

when print population, prints values population = int(words[1]) - indexerror: list index out of range. don't understand how getting error, when print countryname, absolutely fine, error occurs population. python has access same amount of lines both variables seems population trying access more lines, not understand because doesn't countryname. ideas on why occurring.

you assume file perfect , wrong.

try:     countryname = words[0]     population = int(words[1])     dct[countryname] = population except indexerror:     print("impossible convert line: %s " % line) 

i prefer use log print statement in case, sake of example think it's ok. should print line number if want.

anyway purpose of try/except avoid break program when file doesn't respect format have in mind.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -