【问题标题】:Load a dictionary in python from text file从文本文件中加载python中的字典
【发布时间】:2021-07-26 00:32:32
【问题描述】:

我有一个文本文件 config.txt,其中的数据格式如下。每个键值都在一个新行中。 值是一个字符串列表。

key_inv_single = ['invoice'] 
key_inv_number = ['invoice number', 'invoice no', 'invoice #', 'invoice#'] 
key_inv_date = ['invoice date', 'invoice dt', 'issue date', 'date of invoice', 'date of issue', 'issue dt', 'dt of issue'] 

我想把它反序列化成一个与文件同名的python字典。

{
key_inv_single : ['invoice'] 
key_inv_number : ['invoice number', 'invoice no', 'invoice #', 'invoice#'] 
key_inv_date : ['invoice date', 'invoice dt', 'issue date', 'date of invoice', 'date of issue', 'issue dt', 'dt of issue'] 
}

【问题讨论】:

标签: python list dictionary text deserialization


【解决方案1】:

试试下面的。

from ast import literal_eval
file = open("example.txt")
output = {}
for line in file:
    your_line = line.strip().split('=')
    key = your_line[0]
    lst = literal_eval(your_line[1].strip())
    output[key] = lst

输出

{
'key_inv_single ': ['invoice'], 
'key_inv_number ': ['invoice number', 'invoice no', 'invoice #', 'invoice#'], 
'key_inv_date ': ['invoice date', 'invoice dt', 'issue date', 'date of invoice', 'date of issue', 'issue dt', 'dt of issue']
}

首先,我们读取文件并将密钥分配给名为key 的变量。然后我们使用literal_eval 将值转换为实际的列表类型。然后我们将这些值添加到字典中。

当然这可以使用字典理解来完成,但它并不漂亮。

from ast import literal_eval
file = open("example.txt")
output = {line.strip().split('=')[0]:literal_eval(line.strip().split('=')[1].strip())for line in file}

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2020-03-26
    • 2015-08-26
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多