How to input a certain set of data through the specified keyword in text file?

I’m using python 3.7.

I have several sets of data in the text file dict.txt:

A = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (7, 7): 77, (8, 8): 88, (9, 9): 99}
B = [[ 0  2]
 [ 0  4]
 [ 0  5]
 [ 0  6]]
C = 0.2
D = [1 2 3 4 5]

I want to input Line1 A = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (7, 7): 77, (8, 8): 88, (9, 9): 99} as a dict.

And I want to input B as a ndarray.

But I don’t want to input the data through the method of indexing by line number.

Is there any way I can input the data through the method of indexing by the keyword, like A, B, C, or D?

>Solution :

Instead of using a text file, you could use other serialization techniques like pickle.

A text file is not the right approach to store this and then restore it, without having to do unnecessary parsing of various data structures, especially NumPy array that are not part of standard lib and can’t be reversed using say ast.literal_eval.

It’s much easier to just dump them into a pickle file and load it back(unless there is some importance to dumping them into a text file for a human to read):

>>> A = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (7, 7): 77, (8, 8): 88, (9, 9): 99}
>>> B = numpy.array([[0, 2], [4, 6], [0, 5], [0, 6]])
>>> C = 0.2
>>> D = numpy.array([1, 2, 3, 4, 5])


>>> import pickle
>>> with open("foo.pkl", "wb") as f:
...     pickle.dump({"A": A, "B": B, "C": C, "D": D}, f)
...
>>> with open("foo.pkl", "rb") as f:
...     data = pickle.load(f)
...
>>> data
{'A': {(1, 1): 11, (2, 2): 22, (3, 3): 33, (7, 7): 77, (8, 8): 88, (9, 9): 99}, 'B': array([[0, 2],
       [4, 6],
       [0, 5],
       [0, 6]]), 'C': 0.2, 'D': array([1, 2, 3, 4, 5])}
>>> data["B"]
array([[0, 2],
       [4, 6],
       [0, 5],
       [0, 6]])

Leave a Reply