使用python将字典格式的字符串转换为字典

时间:2019-12-11 06:36:46

标签: python-3.x dictionary

我有一个字典格式的字符串,例如:

{'fossils': [{Synset('dodo.n.01'): {'of', 'is', 'out', 'someone', 'fashion', 
'whose', 'style'},Synset('fossil.n.02'): {'age', 'that', 'an', 'has', 'past', 
'from', 'excavated', 'plant', '(',')', 'and', 'animal', 'in', 'remains', 
'geological', 'soil', 'existed', 'impression', 'of', 'or', 'been', 'the', 'a'},
 Synset('fossil.a.01'): {'of', 'a', 'fossil', 'characteristic'}}], 
'disturbing': [{Synset('disturb.v.01'): {'me', 'This', 'upset', 'thought','book', 
'deeply','move', 'troubling', 'A'}, Synset('agitate.v.06'): {'of', 'or', 
'arrangement', 'the', 'position', 'change'}, Synset('touch.v.11'): {'my', '!', 
'touch', 'Do', 'tamper', 'with', 'CDs', "n't"}, Synset('interrupt.v.02'): {'of', 
'or', 'peace', 'tranquility', 'destroy', 'the', 'I', 'me', 'interrupt', 'Do', 
'reading', 'when', "'m", "n't"}}]}

我想把它转换成字典。字典的格式是

{key: list of dictionaries as value}

请帮助我解决这个问题

谢谢

1 个答案:

答案 0 :(得分:0)

您拥有“对象”(称为Synset)。通常,您可以使用json.loads(str)进行这种转换以获取字典的值。 因为您有对象,所以需要手动修复此问题(在json.loads之前对字符串进行预处理),然后在后期进行处理以使对象归还。

编辑:此外,您有多种类型的寄生函数,可能在加载字符串时使事情变得笨拙。

edit2:当然还有另一个选择(如果您的Synset类是已知的并且您相信它的来源): import Synset # for swift conversion dict_val = eval(dict_like_str) 我还将这些行添加到原始文件中