简体   繁体   中英

extract data from file as a dictonary

could you please advice how to read data from file as a dict.

file contains the following lines:

{'foo1': (0, 10), 'foo2': (0, 9), 'foo3': (0, 20)}
{'foo4': (0, 16), 'foo5': (0, 7), 'foo6': (0, 13), 'foo7': (0, 11)}
{'foo8': (0, 8), 'foo9': (0, 8), 'foo10': (0, 7)}
{'foo11': (0, 8)}

all data in {'key': (value, value)} format. All keys in the file are different.

I'd like to get the following "dict":

{'foo1': (0, 1), 'foo2': (0, 0), 'foo3': (0, 1), 'foo4': (1, 0), 'foo5': (0, 0), 'foo6': (0, 5), 'foo7': (0, 2), 'foo8': (2, 2), 'foo9': (1, 1), 'foo10': (0, 7), 'foo11': (0, 1)}

is it possible to extract dicts from the file as merged dict?

For a moment I get only "list" from the file and stucked at this step

import ast
with open('filename') as f:
    content = [ ast.literal_eval( l ) for l in f.readlines() ] 
    print(content)
    

Output:

[{'foo1': (0, 10), 'foo2': (0, 9), 'foo3': (0, 20)}, {'foo4': (0, 16), 'foo5': (0, 7), 'foo6': (0, 13), 'foo7': (0, 11)}, {'foo8': (0, 8), 'foo9': (0, 8), 'foo10': (0, 7)}, {'foo11': (0, 8)}]

If you are totally confident in this file being innocent and only a dictionary, then you can use the python built-in function eval to get the job done. eg:

myfile = open("file.txt", "r")
mydict = eval(myfile.read())

If this allows any user input into the file, however, this could be used to potentially run arbitrary code on your machine. There are precautions to be took if this is reliant on user input, see the top answer on Python: make eval safe for some ideas.

As you get a list of dictionary in content due to list comprehension. I will modify a little.

import ast
content = {}
with open('filename') as f:
    content = content.update(content,ast.literal_eval( l ) for l in f.readlines())
print(content)

See if it works I am beginner. I learned how to merge dictionary from below link. https://levelup.gitconnected.com/7-different-ways-to-merge-dictionaries-in-python-30148bf27add

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM