方法一: 通过内置函数eval

str_info = '{"name": "test", "age": 18}'
dict_info = eval(str_info) print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
print(dict_info) s_info = "{'name': 'nock', 'age': 18}"
d_info = eval(s_info) print("string info type is -->: %s" % (type(s_info)))
print("dict info type is -->: %s" % (type(d_info)))
print(d_info)

  

F:\python\python35\python.exe E:/code/clself/Test/test_example1.py
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
{'name': 'test', 'age': 18}
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
{'name': 'nock', 'age': 18} Process finished with exit code 0

  

不过使用eval有一个安全性问题

方法二: 通过json模块处理

import json
str_info = '{"name": "test", "age": 18}'
dict_info = json.loads(str_info) print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
print(dict_info) s_info = "{'name': 'nock', 'age': 18}"
d_info = json.loads(s_info) print("s info type is -->: %s" % (type(s_info)))
print("d info type is -->: %s" % (type(d_info)))
print(d_info)

结果如下:

F:\python\python35\python.exe E:/code/clself/Test/test_example1.py
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
{'name': 'test', 'age': 18}
Traceback (most recent call last):
File "E:/code/clself/Test/test_example1.py", line 10, in <module>
d_info = json.loads(s_info)
File "F:\python\python35\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "F:\python\python35\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "F:\python\python35\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) Process finished with exit code 1

  

使用json模块进行转换存在一个问题,由于json语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号

方法三: 通过ast模块处理【推荐使用】

import ast
str_info = '{"name": "test", "age": 18}'
dict_info = ast.literal_eval(str_info) print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
print(dict_info) s_info = "{'name': 'nock', 'age': 18}"
d_info = ast.literal_eval(s_info) print("s info type is -->: %s" % (type(s_info)))
print("d info type is -->: %s" % (type(d_info)))
print(d_info)
F:\python\python35\python.exe E:/code/clself/Test/test_example1.py
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
{'name': 'test', 'age': 18}
s info type is -->: <class 'str'>
d info type is -->: <class 'dict'>
{'name': 'test', 'age': 18}

使用ast.literal_eval进行转换既不存在使用json 模块进行转换的问题,也不存在使用eval模块进行转换的安全性问题,因此推荐大家使用ast.literal_eval的方法。

Python字符串转为字典方法大全的更多相关文章

  1. Python 如何将字符串转为字典

    在工作中遇到一个小问题,需要将一个 python 的字符串转为字典,比如字符串: user_info = '{"name" : "john", "ge ...

  2. Python 字符串转换为字典(String to Dict)

    一.需求 为了处理从redis中拿到的value,如下 {"appId":"ct","crawlSts":false,"healt ...

  3. python字符串/列表/字典互相转换

    python字符串/列表/字典互相转换 目录 字符串与列表 字符串与字典 列表与字典 字符串与列表 字符串转列表 1.整体转换 str1 = 'hello world' print(str1.spli ...

  4. python字符串操作实方法大合集

    python字符串操作实方法大合集,包括了几乎所有常用的python字符串操作,如字符串的替换.删除.截取.复制.连接.比较.查找.分割等,需要的朋友可以参考下:   #1.去空格及特殊符号 s.st ...

  5. 【VS开发】CString 转为 char *方法大全

    [VS开发]CString 转为 char *方法大全 标签(空格分隔): [VS开发] 方法1: CString strTemp; char szTemp[128]; strTemp = _T(&q ...

  6. python 列表转为字典的两个小方法

    1.现在有两个列表,list1 = ['key1','key2','key3']和list2 = ['1','2','3'],把他们转为这样的字典:{'key1':'1','key2':'2','ke ...

  7. python字符串内置方法

    网上已经有很多,自己操作一遍,加深印象. dir dir会返回一个内置方法与属性列表,用字符串'a,b,cdefg'测试一下 dir('a,b,cdefg') 得到一个列表 ['__add__', ' ...

  8. Python 字符串分割的方法

    在平时工作的时候,发现对于字符串分割的方法用的比较多,下面对分割字符串方法进行总结一下:第一种:split()函数split()函数应该说是分割字符串使用最多的函数用法:str.split('分割符' ...

  9. 7.python字符串-内置方法分析

    上篇对python中的字符串内置方法进行了列举和简单说明,但这些方法太多,逐一背下效率实在太低,下面我来对这些方法按照其功能进行总结: 1.字母大小写相关(中文无效) 1.1 S.upper() -& ...

随机推荐

  1. Linq学习(五)-多表连接

    本将主要介绍 内连接与 外连接 1.join Linq to sql from a in Blog_Users join b in Blog_UserInfo on a.UserId equals b ...

  2. java学习笔记_BeatBox(GUI部分)

    import java.awt.*; import javax.swing.*; public class BeatBox { JFrame theFrame; JPanel mainPanel; S ...

  3. 电源管理POWER_SUPPLY_PROP_CAPACITY_LEVEL

    电量计节点中有capacity_level 节点,这个是反应当前电池电流高低水平的参数. 分为critical low full normal 一般是由fg的芯片来判断,通过IIC读取,具体判断可参考 ...

  4. Windows开发小问题集

    ON_BN_KILLFOCUS无效,因为需要BS_NOTIFY

  5. TextOut与DrawText的区别

    BOOL TextOut( HDC hdc, // 句柄 int nXStart, // 字符串的开始位置 x坐标 int nYStart, // 字符串的开始位置 y坐标 LPCTSTR lpStr ...

  6. Angular——tab切换案例

    基本介绍 angular框架下的tab切换,相比较于之前的纯js写的代码,有一个很大的特点就是以数据为驱动,基本上不用搜索dom元素就可以实现效果 基本使用 (1)导航部分使用的是的状态使用的是ng- ...

  7. DDX DDV 用法

    DDX:Dialog Data Exchange 如果使用DDX机制,一般会在OnInitDialog消息处理函数或Dialog构造函数中,为对话框对象的成员变量设置了初始值.在对话框显示前,框架的D ...

  8. CAD从二制流数据中加载图形(com接口VB语言)

    主要用到函数说明: _DMxDrawX::ReadBinStream 从二制流数据中加载图形,详细说明如下: 参数 说明 VARIANT varBinArray 二制流数据,是个byte数组 BSTR ...

  9. python学习笔记--关于函数的那点事1

    函数参数 1.位置参数 类似于java函数的基本参数,按照顺序和结构定义参数 2.默认参数 def method(param,defaultParam=defaultValue) 调用时,可以调用me ...

  10. Unittest加载执行用例的方法总结

    前言 说到测试框架,unittest是我最先接触的自动化测试框架之一了, 而且也是用的时间最长的, unittest框架有很多方法加载用例,让我们针对不同的项目,不同项目的大小及用例的多少自己选择加载 ...