Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse defaultdict string

I have dumped multiple defaultdict with a simple print command, like this:

defaultdict(<type 'list'>, {'actual': [20000.0, 19484.0, 19420.0], 'gold': [20000.0, 19484.0, 19464.0]})

Is there some standard parser I could use to retrieve them? I understand I should have used pickle, but the code that generated these defaultdict's is very slow and I'd like to avoid rerunning it.

like image 770
user1451817 Avatar asked Sep 05 '26 14:09

user1451817


1 Answers

If the type of your defaultdict is always <type 'list'>, you can use the following:

from collections import defaultdict

s = """
defaultdict(<type 'list'>, {'actual': [20000.0, 19484.0, 19420.0], 'gold': [20000.0, 19484.0, 19464.0]})
"""
data = eval(s.replace("<type 'list'>", 'list'))

People will tell you that eval() is unsafe and evil, but if someone was trying to inject harmful code into the data that you dumped, they could probably just as easily edit your source code. If the text files you are grabbing this data from is more accessible than your source code, then you might not want to use this method.

If there are multiple types for your defaultdicts, but they are all built-in types (or easy to translate between repr and the type name), then you could still use this method with multiple replacements, for example:

for rep, typ in ((repr(list), 'list'), (repr(dict), 'dict')):
    s = s.replace(rep, typ)
data = eval(s)
like image 189
Andrew Clark Avatar answered Sep 07 '26 04:09

Andrew Clark