Home > Software design >  retrieving multiple dictionaries in list type from file python
retrieving multiple dictionaries in list type from file python

Time:09-28

I want to retrieve the dictionaries of a list after having passed that list to a file. But I lose the format of the contents of the list when I write it in a text. How can I recover this data formatted in dictionaries types again?

first I created a list with two dimensions. then I filled in the values ​​with empty dictionaries and dictionaries with values.

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 [{}, {}, {}, {}, {}]

CodePudding user response:

to retrieve a dict passed as a string, you can use eval (current_place = eval(line[:-1])) but as it can run code it's very unsecure, don't do it if you don't trust the source. the most common way of storing dicts is 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)
  • Related