方法一: 通过内置函数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. android GPS 定位,取位置信息

    现在很多app ,需要取位置信息,所以我也做了一个模块用来取位置信息:   加入位置服务所需的权限: <uses-permission android:name="android.pe ...

  2. 1CSS简介

    -------------------------------------------------------------------------------------------------- - ...

  3. 【RTTI】java Class类详解

    RTTI (Run-Time Type Information)运行时类信息 Java的Class类是java反射机制的基础,通过Class类我们可以获得关于一个类的相关信息,下面我们来了解一下有关j ...

  4. Windows10开启热点

    1.以网线的连接方式,已经连接. 2.打开CMD 3. 开启热点 3.1设置热点名称和密码 netsh wlan set hostednetwork mode=allow ssid=name key= ...

  5. 基于openstack平台的几种Cloud DB解决方案

    方案一.openstack 官方 trove解决方案 此方案进行过镜像的打包,由于网络问题,还未能成功实现 方案二.salt 或者ansible+ docker 由于 docker部署数据库,在数据库 ...

  6. JS——数组

    concat:连接两个或多个数组,返回被连接数组的一个副本. var arr1 = [12, "你好", "哈哈"] var arr2 = [12, " ...

  7. Linq处理decimal字段汇总Sum()为NULL

    xxxxxxxx.Sum(f => f.jifen).GetValueOrDefault(0)

  8. 用Grunt进行CSS文件压缩

    假设你的项目的CSS文件全部放在项目目录下名为css的文件夹中,现在将它压缩合并成一个名为main-min.css的文件,放在css-min文件夹下. (1)首先保证机器安装了node.js. (2) ...

  9. tac

    功能说明:反向显示文件内容. 参数选项: -b 在行前而非行尾加分隔标志. -r 将分隔标志视作正则表达式来解析. -s 使用指定字符串代替换行作为分隔标志.   cat命令与tac命令的对比:

  10. Python星号表达式

    有时候可能想分解出某些值然后丢弃它们,可以使用诸如 _ 或者 ign(ignored)等常用来表示待丢弃值的变量名: record = ('ACME', 50, 123.45, (12, 18, 20 ...