I have a file that I’m reading in and splitting and pushing into a dictionary. I keep getting an error and I think its because the street addresses contain a comma (,).
Here is my file contents:
axe99:315 W. 115th Street, Apt. 11B:New York:NY:10027
jab44:23 Rivington Street, Apt. 3R:New York:NY:10002
ap172:19 Boxer Rd.:New York:NY:10005
jb23:115 Karas Dr.:Jersey City:NJ:07127
jb29:119 Xylon Dr.:Jersey City:NJ:07127
ak9:234 Main Street:Philadelphia:PA:08990
Here is my code:
f2data = open('ex1.txt')
for line in f2data:
print line.strip().split(':')
city_dict = dict(item.split(':') for item in line.strip('\n').split(','))
print city_dict
It keeps throwing this error:
['jk43', '23 Marfield Lane', 'Plainview', 'NY', '10023']
city_dict = dict(item.split(':') for item in line.strip('\n').split(','))
ValueError: dictionary update sequence element #0 has length 5; 2 is required
I’m new to Python and really have no idea what this error means, any thoughts greatly appreciated!
You are getting the error because you are trying to push a list with 5 items into a dictionary constructor when it only takes two items (in the dict constructor python thinks you are using):
here is a list of possible constructors
taken from python docs
you will need to split your string differently or find a better way of formatting your data.
If you are reading from a
csvfile, refer to Michael Hoffman’s answer, which is the correct way to read from a csv.If not, please specify what you are doing and why.
EDIT: Goal added, answer updated
for input:
the code:
will output what you desire:
{'NY': 3, 'NJ': 2, 'PA': 1}