L
L
Lera Kruk2021-07-13 14:30:09
Python
Lera Kruk, 2021-07-13 14:30:09

How to correctly read a file with data types preserved?

There is a data file (0:[2,4,5]), how to read this file to get a dictionary {0:[2,4,5]. Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vindicar, 2021-07-13
@Vindicar

You have to write a parser.
Depending on the complexity of the data structure, it can be moderately difficult or very difficult.
For example, does the data always contain a single-level dictionary with numeric keys and values ​​as a list of numbers, like in your example? Or maybe there are options?
For simple cases, you can parse the string manually. For complex ones, you will have to enter a tool for creating parsers like ANTLR.

A
Alexander, 2021-07-13
@shabelski89

you do not need to write anything, you need to save the data file in valid JSON.
ex:
{"0": [1,2,3]}
read

import json

with open('some_file.txt') as jfile:
    data = json.load(jfile)
    
data
{'0': [2, 4, 5]}
data['0']
[2, 4, 5]
data['0'][0]
2
type(data['0'][0])
<class 'int'>

O
o5a, 2021-07-14
@o5a

If the structure is always something like this, then you can use ast

from ast import literal_eval

s = "0:[2,4,5]"
data = literal_eval(f"{{{s}}}")
print(data)
# {0: [2, 4, 5]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question