How can I fix ValueError: Too many values to unpack" in Python? -


i trying populate dictionary contents of text file ("out3.txt").

my text file of form:

vs,14100  mln,11491  the,7973  cts,7757 

...and on...

i want dictionary answer of form:

answer[vs]=14100  answer[mln]=11491 

...and on...

my code is:

import os import collections import re collections import defaultdict  answer = {} answer=collections.defaultdict(list) open('out3.txt', 'r+') istream:     line in istream.readlines():         k,v = line.strip().split(',')         answer[k.strip()].append( v.strip()) 

but, get:

valueerror: many values unpack

how can fix this?

you have empty lines in input file , suspect 1 of lines have not shared has many commas in (hence "too many values unpack").

you can protect against this, so:

import collections  answer = collections.defaultdict(list) open('out3.txt', 'r+') istream:     line in istream:         line = line.strip()         try:             k, v = line.split(',', 1)             answer[k.strip()].append(v.strip())         except valueerror:             print('ignoring: malformed line: "{}"'.format(line))  print(answer) 

note: passing 1 str.split(), after first comma assigned v; if not desired behaviour , you'd prefer these lines rejected, can remove argument.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -