Trying To Make A Python Dictionary From A File But I Keep Getting Errors Like 'too Many Values To Unpack'
Solution 1:
Most likely some of the countries (e.g. New Zealand) have more than one word in their names and so split()
is returning more than two items, but you're trying to assign the results to two variables regardless. Limit the split
to one:
key, value = line.split(None, 1)
If you find you're getting excess whitespace at the end, throw a strip()
in there:
key, value = line.strip().split(None, 1)
Solution 2:
It looks like you want to split description from a country code... The following will cater for empty descriptions or descriptions of more than one word
withopen('input') as fin:
country_lookup = dict(line.strip().partition(' ')[::2] for line in fin)
Solution 3:
Use this amazing function instead:
defparse_country_codes(file_path):
withopen(file_path) as f:
returndict(line.split(None, 1) for line in f if line)
Solution 4:
What's happening is one of your lines in your file has more than one space, so a line may look like this:
hi hello hey
When doing line.split()
, you're getting:
['hi', 'hello', 'hey']
Which you're trying to assign to two variables, but there are 3 elements in the list. Thus the error.
To avoid this, you would have to either refine your split so it only splits once, or split once only:
key, value = line.split(' ', 1)
Or, if you're using python 3, you can unpack the rest of the list to the value:
key, *value = line.split()
Solution 5:
One of your lines must have more than one space so split()
returns more than the two values expected by key,value = line.split()
.
Post a Comment for "Trying To Make A Python Dictionary From A File But I Keep Getting Errors Like 'too Many Values To Unpack'"