python中dict与str类型转换

在Python 中的“dict”和“str”类型转换:

第一种:“dict”转为“str”:mystr=str(dict1)

              “str”转为“dict”:mydict=eval(mystr)

>>> user="{'name' : 'jim', 'sex' : 'male', 'age': 18}"
>>> exec("c="+user)
>>> c
{'name': 'jim', 'sex': 'male', 'age': 18}
>>> type(user)
<class 'str'>
>>> type(c)
<class 'dict'>

第二种: 使用simplejson把JSON转化为Python内置类型

JSON到字典转化:
ret_dict = simplejson.loads(json_str)
字典到JSON转化:
json_str = simplejson.dumps(dict)

参考:https://blog.csdn.net/anxin997483092/article/details/79223410

猜你喜欢

转载自blog.csdn.net/weixin_41770169/article/details/88034416