Search code examples
pythonpython-3.xdictionarytext-filesvalueerror

Converting text file into dictionary python


I have a text file similar to this:

banana
delicious
yellow

watermelon
big
red

orange
juicy
vitamin c

And I'm trying to convert this text file as dictionary (fruit names as key and its few lines of descriptions as various values). Following is my current code.

f = open("filepath", 'w')
myplant = {}
for line in f:
    k, v = line.strip().split('\n\n')
    myplant[k.strip()] = v.strip()
f.close()

But I got the following error:

ValueError: not enough values to unpack (expected 2, got 1)

Can anyone help me debug my problem. Thank you!


Solution

  • When you iterate over f, you are iterating over lines delimited by '\n', so there will *never be '\n\n' in a single line, only ever one, so .split('\n\n') will never have two value, because there is no occurrence of '\n\n' in the line. That is the source of your error.

    The following is a "cute" way to solve this. I encourage you to figure out another approach on your own, though.

    In [1]: !cat filepath.txt
    banana
    delicious
    yellow
    
    watermelon
    big
    red
    
    orange
    juicy
    vitamin c
    
    
    In [2]: import itertools
    
    In [3]: result = {}
       ...: with open('filepath.txt') as f:
       ...:     for empty_line, group in itertools.groupby(f, lambda x: x == '\n'):
       ...:         if empty_line:
       ...:             continue
       ...:         fruit, *desc = map(str.strip, group)
       ...:         result[fruit] = desc
       ...:
    
    In [4]: result
    Out[4]:
    {'banana': ['delicious', 'yellow'],
     'watermelon': ['big', 'red'],
     'orange': ['juicy', 'vitamin c']}