将文件读入带有和不带分隔符的python字典中

时间:2017-02-02 17:22:03

标签: python parsing dictionary

我试图找到一种在python中将文件解析为字典的快速方法。该文件有一堆行,一些有感兴趣的值,有些没有如下:

Not of interest
Key1=Value1
Not of interest
Key2=Value2
Key3=Value3

如果我编辑文件并删除所有我不感兴趣的行,我可以运行以下命令:

>>> dict(item.split("=") for item in open("testfile"))
{'Key3': 'Value3\n', 'Key2': 'Value2\n', 'Key1': 'Value1\n'}

但在其他方面,我得到以下内容:

>>> dict(item.split("=") for item in open("testfile"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

我认为实现这一目标的一种方法是将整个文件读入列表,创建一个只包含有趣行的新列表,然后针对该列表运行上述命令。

我真的很感激任何人都可以评论最好的方法。

2 个答案:

答案 0 :(得分:3)

您应该使用=关键字查看该行中是否有in

dict(item.split("=") for item in open("testfile") if "=" in item)

答案 1 :(得分:0)

所以我想出的最好的是:

>>> import re
>>> file = open("test").readlines()
>>> dict(item.split("=") for item in [line for line in file if re.match('.*=.*', line)])
{'Key3': 'Value3\n', 'Key2': 'Value2\n', 'Key1': 'Value1\n'}
>>>>

如果有更好的方法,我仍然欢迎反馈,但如果不希望它对某人有用!

克里斯

相关问题