你當時幾乎沒有;你應該使用key
在詞典中的關鍵,不是file
:
(key, val) = line.split(': ')
d[key] = val.rstrip('\n')
我添加了一個str.strip()
通話;大概你不需要在每行結尾存儲換行符。
但是,您需要單獨分析購買列表,因爲這些不適合您的key: value
模式。我在這裏假設它是最後條目列表:
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')
當你閱讀List of purchases
線這將讀取文件的剩餘部分爲一個單獨的列表。
演示:
>>> 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 '}
什麼是你期望的輸出? – 2015-03-25 11:58:37
我必須得到的關鍵:值對成字典, – 2015-03-25 12:06:52