【问题标题】:retrieving multiple dictionaries in list type from file python从文件python中检索列表类型的多个字典
【发布时间】:2021-09-26 20:55:36
【问题描述】:

我想在将列表传递给文件后检索列表的字典。但是当我将其写入文本时,我会丢失列表内容的格式。如何再次恢复以字典类型格式化的数据?

首先我创建了一个二维列表。然后我用空字典和带值的字典填充值。

dataValue = {
        'telefone': '6298855663311',
        'nome': '', 
        'pagamento': 'Boleto', 
        'embarque': '16:00'
}

emptyDi = {}

assentosMatriz2D = [

        [dataValue, emptyDi, emptyDi, emptyDi, emptyDi],
        
        [emptyDi, emptyDi, emptyDi, emptyDi, emptyDi],
        
    [emptyDi, emptyDi, dataValue, emptyDi, emptyDi]

    ]

print(assentosMatriz2D[0][1])

with open('listfile.txt', 'w') as f:
    f.writelines("%s\n" % place for place in assentosMatriz2D)

# define empty list
linhas = []

# open file and read the content in a list
with open('listfile.txt', 'r') as f:
    filecontents = f.readlines()

    for line in filecontents:
        # remove linebreak which is the last character of the string
        current_place = line[:-1]

        # add item to the list
        linhas.append(current_place)

create_lt = linhas[1]

print(create_lt[0][0])

print(f'the firt line {create_lt}')

output:::::
>>{}
>>[
>>the firt line [{}, {}, {}, {}, {}]

【问题讨论】:

    标签: python-3.x list file dictionary formatting


    【解决方案1】:

    要检索作为字符串传递的 dict,您可以使用 eval (current_place = eval(line[:-1])) 但由于它可以运行代码,因此非常不安全,如果您不信任来源,请不要这样做。最常用的 dicts 存储方式是 json

    import json
    with open('listfile.txt', 'w') as f:
        json.dump(assentosMatriz2D, f)
    
    # open file and read the content in a list
    with open('listfile.txt', 'r') as f:
        assentosMatriz2D = json.load(f)
    

    【讨论】:

    • 非常感谢,包括这个关于安全的提示!非常重要,但幸运的是,此代码适用于大学
    猜你喜欢
    • 2020-01-28
    • 2020-07-23
    • 2020-04-28
    • 2018-02-12
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2016-04-23
    相关资源
    最近更新 更多