Python turn text file into dictionary

后端 未结 2 641
生来不讨喜
生来不讨喜 2021-01-28 09:18

I\'m writing a spell checking function and I have a text file that looks like this

teh the
cta cat
dgo dog
dya day
frmo from
memeber member

Th

2条回答
  •  天命终不由人
    2021-01-28 10:22

    Use this:

    with open('dictionary.txt') as f:
        d = dict(line.strip().split(None, 1) for line in f)
    

    d is the dictionary.

    disclaimer: This will work for the simple structure you have illustrated above, for more complex file structures you will need to do much more complex parsing.

提交回复
热议问题