Importing string as an ordered dictionary

≡放荡痞女 提交于 2021-02-07 19:59:02

问题


I have a file with no extension with lines like this (ignore the spacing between the lines, but each line is a separate row):

OrderedDict([('key1', u'value1'), ('key2', 'value2')])
OrderedDict([('key1', u'value1'), ('key2', 'value2')])
OrderedDict([('key1', u'value1'), ('key2', 'value2')])

when I import it to Python

snap_fh = open("C:\Users\.......")
for row in snap_fh:
    print(type(row))

rows are "strings" and I cannot parse it as an OrderedDictionary

"OrderedDict([('key1', u'value1'), ('key2', 'value2'))])\n"

How can I import it as an OrderedDict

ast.literal_eval(row) did not work !


回答1:


You should use a regular expression for safer evaluation:

import re
import ast
from collections import OrderedDict

def read(f):
    for s in f:
        m = re.match(r'^OrderedDict\((.+)\)$', s)
        if m:
            yield OrderedDict(ast.literal_eval(m.group(1)))

...
for d in read(snap_fh):
    print type(d)



回答2:


Using eval seems to work nicely

s = "OrderedDict([('key1', u'value1'), ('key2', 'value2')])"
a = eval(s, {'OrderedDict': OrderedDict})
print (a)

Use it only if you trust the source of your inputs - since eval is very risky



来源:https://stackoverflow.com/questions/34797928/importing-string-as-an-ordered-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!