1

I have a function that I want to open .dat files with, to extract data from them, but the problem is I don't know how to turn that data back into a dictionary to store in a variable. Currently, the data in the files are stored like this: "{"x":0,"y":1}" (it uses up only one line of the file, which is just the normal structure of a dictionary).

Below is just the function where I open the .dat file and try to extract stuff from it.

def openData():
    file = fd.askopenfile(filetypes=[("Data",".dat"),("All Files",".*")])
    filepath = file.name
    if file is None:
        return
    with open(filepath,"r") as f:
        contents = dict(f.read())
        print(contents["x"]) #let's say there is a key called "x" in that dictionary

This is the error that I get from it: (not because the key "x" is not in dict, trust me)

Exception in Tkinter callback
Traceback (most recent call last):
  File "...\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "...\PycharmProjects\[this project]\main.py", line 204, in openData
    contents = dict(f.read())
ValueError: dictionary update sequence element #0 has length 1; 2 is required

Process finished with exit code 0

Update: I tried using json and it worked, thanks to @match

def openData():
    file = fd.askopenfile(filetypes=[("Data",".dat"),("All Files",".*")])
    filepath = file.name
    if file is None:
        return
    with open(filepath,"r") as f:
        contents = dict(json.load(f))
        print(contents["x"])
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 2
    This looks like it might be `json` in which case you can just use the `json` library to easily load it. – match Jan 04 '22 at 15:57
  • 1
    @match I can't really put a tick on your comment to show that it worked, but yes I tried doing json things and it worked. – danielshmaniel Jan 04 '22 at 16:17

1 Answers1

0

You need to parse the data to get a data structure from a string, fortunately, Python provides a function for safely parsing Python data structures: ast.literal_eval(). E.g:

import ast

...

with open("/path/to/file", "r") as data:
    dictionary = ast.literal_eval(data.read())

Reference stackoverflow

Franz Kurt
  • 1,020
  • 2
  • 14
  • 14