行ごとに処理します。
with open('lottery.txt', 'r') as fop:
result = dict(map(str.strip, line.split(':', 1)) for line in fop)
はジェネレータ式dict(map(..) for line in fop)
を使用しています。行ごとにループし、最初に見つけたコロンでその行を 2 つの値に分割し、その削除された結果をマッピングのキーと値として保存します。fop
:
map(str.strip, line.split(':', 1))
は、分割行の各部分の開始と終了から空白を削除します。それ自体は、ペアのみを必要とするコンストラクターが行の余分なコロンによって混乱するのを防ぐために、そのような文字.split()
の分割を 1 つのみに制限します。:
:
dict
(key, value)
デモ:
>>> open('/tmp/lottery.txt', 'w').write(' monday: 2 23\ntuesday :4 31\nwednesday : 19 22\nthursday : 1')
>>> with open('/tmp/lottery.txt', 'r') as fop:
... result = dict(map(str.strip, line.split(':', 1)) for line in fop)
...
>>> result
{'tuesday': '4 31', 'thursday': '1', 'wednesday': '19 22', 'monday': '2 23'}
長い非ジェネレータ式のバージョンは次のようになります。
with open('lottery.txt', 'r') as fop:
result = {}
for line in fop:
key, value = line.split(':', 1)
result[key.strip()] = value.strip()