jim*_*jim 7 python formatting dictionary key
假设我有一个包含以下内容的文本文件:
line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"
Run Code Online (Sandbox Code Playgroud)
我想快速将这些转换为字典键/值,其中"line*"是键,引号中的文本作为值,同时还删除等号.
在Python中执行此操作的最佳方法是什么?
ins*_*get 16
f = open(filepath, 'r')
answer = {}
for line in f:
k, v = line.strip().split('=')
answer[k.strip()] = v.strip()
f.close()
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
在一行中:
d = dict((line.strip().split(' = ') for line in file(filename)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30120 次 |
| 最近记录: |