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

标签 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 中执行此操作的最佳方法是什么?

最佳答案

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

f.close()

希望对你有帮助

关于Python - 轻松将文本文件内容转换为字典值/键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5942874/

相关文章:

java - 如何将其他区域设置中的数字格式化为正常区域设置

python - 如何在 python Pandas 中执行/解决条件连接?

Python ftplib 损坏文件?

c++ - C++中这些之间有什么区别?

formatting - d3.js:tickformat - 添加一个 % 符号而不乘以 100

java - Java中的双十进制格式

python - 尝试写入字典中的特定键,但它正在写入整个字典中的所有键

python - 在Python中扫描目录并重命名文件

python - 将字典转换为元组,并在元组内添加其他元素

java - O(1) 中的 value.contains(object) 的高效 java 映射?