0

In a file like:

 jaslkfdj,asldkfj,,,
 slakj,aklsjf,,,
 lsak,sajf,,,

how can you split it up so there is just a key value pair of the two words? I tried to split using commas but the only way i know how to make key/value pairs is when there is only one commma in a line.

python gives the error: "ValueError: too many values to unpack (expected 2)" because of the 3 extra commas at the end of each line

this is what i have:

newdict= {}
wd = open('file.csv', 'r')
for line in wd:
      key,val = line.split(',')
      newdict[key]=val
print(newdict)
  • `split()` with a limit, `rstrip()` to discard the rest. – Wrikken Oct 10 '13 at 22:01
  • Please show the code you tried, instead of just describing it and making us guess which of the billion possible things that could be wrong with it is the one that you actually faced. – abarnert Oct 10 '13 at 22:03
  • 1
    @abarnet this is the third iteration of this question: 1st: http://stackoverflow.com/questions/19304591/converting-file-to-key-value-dictionary and 2nd: http://stackoverflow.com/questions/19305666/word-dictionary-problems – Jon Clements Oct 10 '13 at 22:08
  • thank you @abarnet i didn't know there was a limit to the number of questions you can ask – user2844776 Oct 10 '13 at 22:15
  • @user2844776: There is no limit to the number of questions you can ask—but they should all be good and useful questions. – abarnert Oct 10 '13 at 22:31

3 Answers3

2

Try slicing for the first two values:

"a,b,,,,,".split(",")[:2]

Nice summary of slice notation in this answer.

Community
  • 1
  • 1
istruble
  • 13,363
  • 2
  • 47
  • 52
2

It seems more likely that what you tried is this:

>>> line = 'jaslkfdj,asldkfj,,,'
>>> key, value = line.split(',')
ValueError: too many values to unpack (expected 2)

There are two ways around this.

First, you can split, and then just take the first two values:

>>> line = 'jaslkfdj,asldkfj,,,'
>>> parts = line.split(',')
>>> key, value = parts[:2]

Or you can use a maxsplit argument:

>>> line = 'jaslkfdj,asldkfj,,,'
>>> key, value = line.split(',', 1)

This second one will leave extra commas on the end of value, but that's easy to fix:

>>> value = value.rstrip(',')
abarnert
  • 354,177
  • 51
  • 601
  • 671
0
with open('file.csv', 'r') as wd:
    newdict = dict(line.split(",")[:2] for line in wd.read().splitlines())

print newdict

The result is follows:

{' jaslkfdj': 'asldkfj', ' lsak': 'sajf', ' slakj': 'aklsjf'}

Buddy
  • 1,808
  • 3
  • 19
  • 28