Python - 轻松地将文本文件内容转换为字典值/键

时间:2011-05-09 21:46:24

标签: python dictionary formatting key

假设我有一个包含以下内容的文本文件:

line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"

我想快速将这些转换为字典键/值,其中“line *”是键,引号中的文本作为值,同时也删除等号。

在Python中执行此操作的最佳方法是什么?

3 个答案:

答案 0 :(得分:15)

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

f.close()

希望这有帮助

答案 1 :(得分:5)

在一行中:

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

答案 2 :(得分:0)

以下是urlopen版本的inspectorG4dget的答案可能如下:

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()