简体   繁体   English

如何将默认值dict字符串转换为实际dict

[英]How to convert a dict string with value default dict to an actual dict

I am trying to convert the following string to a dict: 我正在尝试将以下字符串转换为字典:

"{'key1': 0, 'key2': defaultdict(<class 'int'>, {'total': 9, 'semcor': 9})}"

I tried using literal_eval from ast and also json.loads from json, however none of them can convert it. 我尝试使用ast的literal_eval和json的json.loads,但是他们都不能转换它。 For JSON I understand that it does not have the json structure, however I don't fully understand why literal_eval doesn't work. 对于JSON,我知道它没有json结构,但是我不完全理解为什么literal_eval无法正常工作。

Can someone tell me if it is possible to do so? 有人可以告诉我是否可以这样做?

A quick and dirty way to parse it is to replace the <class 'int'> notation with the actual class name, and then eval the string: 一种快速而肮脏的解析方法是用实际的类名替换<class 'int'>表示法,然后eval字符串:

from collections import defaultdict
import re
s = '''"{'key1': 0, 'key2': defaultdict(<class 'int'>, {'total': 9, 'semcor': 9})}"'''
eval(re.sub(r"<class '(\w+)'>", r'\1', s))

This returns: 返回:

{'key1': 0, 'key2': defaultdict(int, {'total': 9, 'semcor': 9})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM