Answer the question
In order to leave comments, you need to log in
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
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.
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'>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question