字符串到python中的OrderedDict转换

sre*_*rek 3 python string parsing ordereddictionary

我通过导入集合创建了一个python Ordered Dictionary并将其存储在名为'filename.txt'的文件中.文件内容看起来像

OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3)])
Run Code Online (Sandbox Code Playgroud)

我需要从另一个程序中使用这个OrderedDict.我这样做

myfile = open('filename.txt','r')
mydict = myfile.read()
Run Code Online (Sandbox Code Playgroud)

我需要获得类型的'mydict'

<class 'collections.OrderedDict'>
Run Code Online (Sandbox Code Playgroud)

但在这里,它出现了'str'类型.
有没有办法在python中将字符串类型转换为OrderedDict类型?使用python 2.7

won*_*ng2 7

你可以用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'>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,泡菜可能与eval一样危险.不要破坏你不能信任的数据 (7认同)

Gar*_*tty 6

最好的解决方案是以不同的方式存储数据。例如,将其编码为JSON

您还可以按照pickle其他答案中的说明使用模块,但这存在潜在的安全问题(如下文eval()所述)-因此,仅当您知道数据将始终受到信任时才使用此解决方案。

如果您无法更改数据格式,那么还有其他解决方案。

真正糟糕的解决方案是使用eval()这样做。这是真的 真的很糟糕的主意,因为它的不安全,如把文件中的任何代码都将运行,连同其他原因

更好的解决方案是手动解析文件。有利的一面是,有一种方法可以使您作弊,并且做起来更轻松。Python具有ast.literal_eval()允许您轻松解析文字的功能。虽然这不是文字,因为它使用OrderedDict,但我们可以提取列表文字并进行解析。

例如:(未经测试)

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))
Run Code Online (Sandbox Code Playgroud)

  • @Cpfohl,c)如果可能+2 (2认同)