在python中将字符串转换为OrderedDict [英] string to OrderedDict conversion in python

查看:220
本文介绍了在python中将字符串转换为OrderedDict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过导入集合创建了python命令字典,并将其存储在名为"filename.txt"的文件中.文件内容看起来像

i have created a python Ordered Dictionary by importing collections and stored it in a file named 'filename.txt'. the file content looks like

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

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

i need to make use of this OrderedDict from another program. i do it as

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

我需要获取类型为的'mydict'

i need to get 'mydict' as of Type

<class 'collections.OrderedDict'>

但是在这里,它的类型为'str'.
python中有什么方法可以将字符串类型转换为OrderedDict类型?使用python 2.7

but here, it comes out to be of type 'str'.
is there any way in python to convert a string type to OrderedDict type? using python 2.7

推荐答案

您可以使用腌制

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'>

这篇关于在python中将字符串转换为OrderedDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆