String to convert OrderedDict to python

I created an ordered python dictionary by importing collections and saved it in a file called 'filename.txt'. the contents of the file look like

OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3)]) 

I need to use this OrderedDict from another program. i do it like

 myfile = open('filename.txt','r') mydict = myfile.read() 

I need to get "mydict" by type

 <class 'collections.OrderedDict'> 

but here it looks like "str".
is there any way in python to convert string type to type OrderedDict? using python 2.7

+1
source share
4 answers

You can save and load it with pickle

 import cPickle as pickle # store: with open("filename.pickle", "w") as fp: pickle.dump(ordered_dict, fp) # read: with open("filename.pickle") as fp: ordered_dict = pickle.load(fp) type(ordered_dict) # <class 'collections.OrderedDict'> 
+7
source

The best solution here is to store your data in a different way. Encode it in JSON , for example.

You can also use the pickle module , as explained in other answers, but this has potential security issues (as explained using eval() below) - so use this solution only if you know that the data will always be trusted.

If you cannot change the data format, then there are other solutions.

A very bad solution is to use eval() for this. This is a really bad idea indeed , because it is unsafe, since any code placed in a file will run along with other reasons

The best solution is to manually parse the file. The good news is that you can fool it and make it a little easier. Python has ast.literal_eval() , which makes it easy to parse literals. Although this is not a literal, since it uses an OrderedDict, we can extract a literal list and parse it.

For example: (unverified)

 import re import ast import collections with open(filename.txt) as file: line = next(file) values = re.search(r"OrderedDict\((.*)\)", line).group(1) mydict = collections.OrderedDict(ast.literal_eval(values)) 
+4
source

This is not a good solution, but it works. :)

 ####################################### # String_To_OrderedDict # Convert String to OrderedDict # Example String # txt = "OrderedDict([('width', '600'), ('height', '100'), ('left', '1250'), ('top', '980'), ('starttime', '4000'), ('stoptime', '8000'), ('startani', 'random'), ('zindex', '995'), ('type', 'text'), ('title', '#WXR#@ TU@ @ Izmir@ @ brief_txt@ '), ('backgroundcolor', 'N'), ('borderstyle', 'solid'), ('bordercolor', 'N'), ('fontsize', '35'), ('fontfamily', 'Ubuntu Mono'), ('textalign', 'right'), ('color', '#c99a16')])" ####################################### def string_to_ordereddict(txt): from collections import OrderedDict import re tempDict = OrderedDict() od_start = "OrderedDict(["; od_end = '])'; first_index = txt.find(od_start) last_index = txt.rfind(od_end) new_txt = txt[first_index+len(od_start):last_index] pattern = r"(\(\'\S+\'\,\ \'\S+\'\))" all_variables = re.findall(pattern, new_txt) for str_variable in all_variables: data = str_variable.split("', '") key = data[0].replace("('", "") value = data[1].replace("')", "") #print "key : %s" % (key) #print "value : %s" % (value) tempDict[key] = value #print tempDict #print tempDict['title'] return tempDict 
0
source

Here's how I did it in Python 2.7

 from collections import OrderedDict from ast import literal_eval # Read in string from text file myfile = open('filename.txt','r') file_str = myfile.read() # Remove ordered dict syntax from string by indexing file_str=file_str[13:] file_str=file_str[:-2] # convert string to list file_list=literal_eval(file_str) header=OrderedDict() for entry in file_list: # Extract key and value from each tuple key, value=entry # Create entry in OrderedDict header[key]=value 

Again, you probably should write your text file in different ways.

0
source

Source: https://habr.com/ru/post/1481679/


All Articles