0

This is what I have so far:

for key,value in spee_dict:
    with open(key, 'w+') as f:
        f.write(value)

I get the following: ValueError: too many values to unpack

Probably this is because I have tens of thousands of words stored as values for each key. There are 893 keys. How can I get around this error?

Edit:

Key and value are all string.

Here are a few example of keys and values for spee_dict:

key      value
speech1  we should have gone to the other country a few years ago
speech2  our tax situation is completely fine and revenues are increasing
speech3  ladies and gentlemen, thank you for your attention
...

Basically, I want in a folder on my U:/ drive files like speech1.txt, speech2.txt, and speech3.txt

blacksite
  • 12,086
  • 10
  • 64
  • 109

1 Answers1

1

Dictionaries iterate on keys only.

Instead use

for key,value in spee_dict.items():
    with open(key, 'w+') as f:
        f.write(value)

In case you are on Python 2, it would make sense to use iteritems instead of items (i.e. it would not produce a list, but a generator)

for key,value in spee_dict.iteritems():
    with open(key, 'w+') as f:
        f.write(value)
Pynchia
  • 10,996
  • 5
  • 34
  • 43
  • Oh, right. for some reason, that doesn't write to my folder at directory: `U:/wordfolder`.. it just runs in the console – blacksite Nov 20 '15 at 21:23
  • 1
    I believe OP wanted to write each value to its own text file with a filename of the corresponding key. – pzp Nov 20 '15 at 21:25
  • 1
    @pzp yes thank you, I just noticed now...... it's the usual [XY Problem](http://xyproblem.info/) that bites – Pynchia Nov 20 '15 at 21:27
  • Also, it's worth mentioning [`dict.iteritems()`](https://docs.python.org/2/library/stdtypes.html#dict.iteritems) for Python 2.x. – pzp Nov 20 '15 at 21:27
  • Did I not make it clear I wanted to write each value to separate files? – blacksite Nov 20 '15 at 21:28
  • @pzp done, thank you for the suggestion – Pynchia Nov 20 '15 at 21:31
  • @GBR24 can you please show: 1) the type and format of the value of each dictionary item (you say `thousands of words stored as values for each key`, are they in a string/list/tuple); 2) exactly what you expect the program to output in each file – Pynchia Nov 20 '15 at 21:41