0

I have to read a text file in python into a dictionary, I have tried several options but I can't get it to work. The format of the text file is the following:

Shop: someshop  
Schedule: from 8:00 to 18:00  
Day: 11:11:2011  
Items Sold: 456  
List of purchases:  
(product, 123, 12:30)    
(product, 123, 12:30)  
(product, 123, 12:30)

I have also tried to use regex, but I can't figure out to get the item on list of purchases.

Here is some code I tried:

d = {}
with open("sometext.txt", "r") as f:
    for line in f:

        (key, val) = line.split(': ')
        d[file] = (key,val)
        print (val)


print d
2
  • What's your expected output? Commented Mar 25, 2015 at 11:58
  • I have to get the key:value pairs into a dict, Commented Mar 25, 2015 at 12:06

1 Answer 1

1

You were almost there; you should use key as the key in the dictionary, not file:

(key, val) = line.split(': ')
d[key] = val.rstrip('\n')

I've added a str.strip() call; presumably you don't need to store the newline at the end of each line.

You'll need to parse the list of purchases separately however, as those don't fit your key: value pattern here. I'm assuming here that it is the last entry in the list:

d = {}
with open("sometext.txt", "r") as f:
    for line in f:
        if line.startswith('List of purchases'):
            purchases = d['List of purchases'] = []
            for line in f:
                info = line.strip('() \n').split(', ')
                purchases.append(info)
            break
        key, val = line.split(': ')
        d[key] = val.rstrip('\n')

This will read the remainder of the file into a separate list when you read the List of purchases line.

Demo:

>>> from io import StringIO
>>> sample = '''\
... Shop: someshop  
... Schedule: from 8:00 to 18:00  
... Day: 11:11:2011  
... Items Sold: 456  
... List of purchases:  
... (product, 123, 12:30)    
... (product, 123, 12:30)  
... (product, 123, 12:30)
... '''
>>> d = {}
>>> with StringIO(sample) as f:
...     for line in f:
...         if line.startswith('List of purchases'):
...             purchases = d['List of purchases'] = []
...             for line in f:
...                 info = line.strip('()\n').split(', ')
...                 purchases.append(info)
...             break
...         key, val = line.split(': ')
...         d[key] = val.rstrip('\n')
... 
>>> d
{'Schedule': 'from 8:00 to 18:00  ', 'List of purchases': [['product', '123', '12:30'], ['product', '123', '12:30'], ['product', '123', '12:30']], 'Day': '11:11:2011  ', 'Shop': 'someshop  ', 'Items Sold': '456  '}
>>> from pprint import pprint
>>> pprint(d)
{'Day': '11:11:2011  ',
 'Items Sold': '456  ',
 'List of purchases': [['product', '123', '12:30'],
                       ['product', '123', '12:30'],
                       ['product', '123', '12:30']],
 'Schedule': 'from 8:00 to 18:00  ',
 'Shop': 'someshop  '}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, but i still get this error code "ValueError: need more than 1 value to unpack", when it gets to last key i can't read the values in the last lines.
Thank you very much. Thumbs up to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.