开发者

Python - converting textfile contents into dictionary values/keys easily

开发者 https://www.devze.com 2023-03-04 06:45 出处:网络
Let\'s say I have a text file with the following: li开发者_如何学Cne = \"this is line 1\" line2 = \"this is the second line\"

Let's say I have a text file with the following:

li开发者_如何学Cne = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"

And I want to quickly convert these into dictionary keys/values with " line* " being the key and the text in quotes as the value while also removing the equals sign.

What would be the best way to do this in Python?


f = open(filepath, 'r')
answer = {}
for line in f:
    k, v = line.strip().split('=')
    answer[k.strip()] = v.strip()

f.close()

Hope this helps


In one line:

d = dict((line.strip().split(' = ') for line in file(filename)))


Here's what the urlopen version of inspectorG4dget's answer might look like:

from urllib.request import urlopen
url = 'https://raw.githubusercontent.com/sedeh/github.io/master/resources/states.txt'
response = urlopen(url)
lines = response.readlines()
state_names_dict = {}
for line in lines:
    state_code, state_name = line.decode().split(":")
    state_names_dict[state_code.strip()] = state_name.strip()
0

精彩评论

暂无评论...
验证码 换一张
取 消