Convert unicode string dictionary into dictionary in python

前端 未结 5 1835

I have unicode u\"{\'code1\':1,\'code2\':1}\" and I want it in dictionary format.

I want it in {\'code1\':1,\'code2\':1} format.

I

5条回答
  •  佛祖请我去吃肉
    2020-12-08 03:02

    You can use literal_eval. You may also want to be sure you are creating a dict and not something else. Instead of assert, use your own error handling.

    from ast import literal_eval
    from collections import MutableMapping
    
    my_dict = literal_eval(my_str_dict)
    assert isinstance(my_dict, MutableMapping)
    

提交回复
热议问题