Python字符串转为字典方法大全

2023-11-11

方法一: 通过内置函数eval

1

2

3

4

5

6

7

8

9

10

11

12

13

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)

  

1

2

3

4

5

6

7

8

9

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模块处理

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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)

结果如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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 10in <module>

    d_info = json.loads(s_info)

  File "F:\python\python35\lib\json\__init__.py", line 319in loads

    return _default_decoder.decode(s)

  File "F:\python\python35\lib\json\decoder.py", line 339in decode

    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File "F:\python\python35\lib\json\decoder.py", line 355in 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)

复制代码

1

2

3

4

5

6

7

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的方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • 使用 PIP 从 Github 安装 Python 包

    我已经看到文档表明您可以通过以下方式使用 pip 安装托管 Python 包的 Github sudo pip install e git git github com myuser myproject git egg myproject
  • 将 3D 矩阵转换为级联 2D 矩阵

    我有一个3Dpython中的矩阵如下 import numpy as np a np ones 2 2 3 a 0 0 0 2 a 0 0 1 3 a 0 0 2 4 我想转换这个3D矩阵到一组2D矩阵 我努力了np reshape但这并没
  • numba.prange 性能不佳

    我试图整理一个简单的例子来说明使用的好处numba prange对于我自己和一些同事来说 但我无法获得像样的加速 我编写了一个简单的一维扩散求解器 它本质上是在一个长数组上循环 组合元素i 1 i and i 1 并将结果写入element
  • DRF ManyToMany Field 在创建对象时出现错误

    我有一个Rant模型与Category使用链接到它ManyToManyField 我已经序列化了它 但问题是这个错误 categories Expected a list of items but got type str 这些是我的序列化
  • 添加图例到散点图

    这个问题已经被问到了 但我想找到一个更清晰的解决方案 给定 X 是 100x2 数据 标签是标签向量 从 1 到 9 我绘制散点图如下 pl scatter X 0 X 1 c labels pl show 如何仅用一行代码添加图例来解释颜
  • 在 Python 中打开 Alteryx .yxdb 文件?

    有没有办法将 yxdb Alteryx 数据库文件 导入到 Pandas Python 中 而不使用 Alteryx 作为中间人 简短的回答是否定的 目前还不行 更长的答案 yxdb 支持的原始 C 是可以在 github 上找到 http
  • python subprocess proc.stderr.read() 引入额外的行?

    我想运行一些命令并抓取输出到 stderr 的任何内容 我有两个版本的函数可以执行此操作 版本 1 def Getstatusoutput cmd Return status output of executing cmd in a she
  • 减少每日状态表以仅包含状态更改

    我有一个包含 10 万以上用户的大型每日状态表 5 7 亿行 目前它位于 MySQL 或 CSV 中 该表包含三列 user id status 和 date 理想情况下 我希望将表缩减为一个新表 其中包含每个状态期间的 user id s
  • QFileDialog 作为 TableView 的编辑器:如何获取结果?

    我正在使用一个QFileDialog作为某些专栏的编辑QTableView 这基本上有效 对一些焦点问题取模 请参阅here https stackoverflow com questions 22854242 qfiledialog as
  • f.read 为空

    我在解释器中完成这一切 loc1 council council1 file1 open loc1 r 此时我可以执行 file1 read 并将文件的内容作为字符串打印到标准输出 但如果我添加这个 string1 file1 read 字
  • scrapy蜘蛛如何将值返回给另一个蜘蛛

    我正在爬行的网站包含许多玩家 当我点击任何玩家时 我都可以进入他的页面 网站结构是这样的
  • 如何在Python中将字符串转换为包含一个元素的列表[重复]

    这个问题在这里已经有答案了 我有一个字符串 我想将其转换为其中只有一个元素的列表 a abc print list a output a b c Expected o p abc 正确的做法是什么 只需使用 a abc b a print
  • 在 pandas 中展开列表列时,是否有一种Python式的方法来添加枚举列?

    考虑以下DataFrame gt gt gt df pd DataFrame A 1 2 3 B abc def ghi apply A int B list gt gt gt df A B 0 1 a b c 1 2 d e f 2 3
  • 将误差线添加到 3D 绘图

    我找不到在 matplotlib 的 3D 散点图中绘制误差条的方法 基本上 对于以下代码段 from mpl toolkits mplot3d import axes3d import matplotlib pyplot as plt f
  • 在地图类型中创建 DataFrame 分组列

    My 数据框具有以下结构 df spark createDataFrame B a 10 B b 20 C c 30 Brand Type Amount df show Brand Type Amount B a 10 B b 20 C c
  • 使用 South 更改 Django 模型列默认值

    我在 Django 项目中使用 South 和 Postgresql DB 我想更改一个模型字段的默认值以供继续使用 我不需要以前的记录 刚刚新记录 我是否需要为此进行迁移 或者只是更改模型 旧场详细信息 background style
  • Python,socket.error:[Errno 10049]

    在开发一个简单的聊天客户端的基础上 遇到以下错误 socket error Errno 10049 The requested address is not valid in its context 代码是 from socket impo
  • 在硬件级别模拟按键 - Windows

    我正在寻找一种语言或库 使我能够在最大可能的水平上模拟击键 而无需实际按下按键 我对击键级别的具体衡量标准是 当我的计算机已经运行按键侦听器 例如鼠标键和粘滞键 时 它是否会产生与物理按键相同的输出 我尝试过很多击键模拟的方法 java A
  • 采用迭代器而不是可迭代的方法[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 关于迭代器和可迭代对象 仅是我的观察 如果我错了 请纠正我 大多数构造函数 数组类型 将迭代器作为质量构造函数 迭代器是显式创建的 或
  • Python - 函数无法在新线程中运行

    我正试图杀死notepad exe使用此函数在 Windows 上进行处理 import thread wmi os print CMD Kill command called def kill c wmi WMI Commands not

随机推荐

  • 有源滤波器治理谐波好在哪

    减小谐波影响应对谐波源本身或在附近采取适当的措施 通常情况下 采用加装滤波器的方式治理谐波 滤波器一般分为无源滤波器和有源滤波器 下面领步 北京 根据多年的实践经验给出一个具体的解决方案 在有谐波问题是 什么样的选择才是最好的 谐波的危害
  • React---使用componentDidUpdate钩子函数判断路由地址是否发生变化

    在组件更新 例如组件的路由更新 后会执行componentDidUpdate钩子函数 componentDidUpdate方法会传入两个参数 prevProps prevState prevProps prevState可以拿到组件更新前的
  • Web3 入门手册:从认知到实践

    如果你也喜欢 Web3 希望在这做些有趣的 有意义的事情 那么我希望这篇文章可以帮助到你 送给想要进入 Web3 或者刚刚进入 Web3 的小伙伴 但是考虑到两点原因 我还是打算把这件事推迟一些时日 一是在各大媒体都鼓吹 All In We
  • 如何将pdf转换成txt?悄悄告诉你3个好用的转换方法

    pdf和txt文档都是我们经常会使用到的文档格式 这两种文档各有各的特点 pdf文档适合用于展示 而txt文档适合用于整理各种文字信息 在面对不同的情况时我们就要使用不同的文档 就比如将纯文字的资料进行搜集的时候 利用txt文档会更方便 而
  • 如何在vue中引入字体

    一 为什么要引入字体 在前端开发中 选用合适的字体往往会极大地提升网站的视觉体验 然而 网页中默认字体的种类和风格有限 且在不同的设备 浏览器上渲染效果不尽相同 因此 很多开发者会选择自定义字体来提升用户体验 二 如何引入字体 1 搜索下载
  • 2020华为杯数学建模总结

    2020研究生数学建模竞赛总结 题目 2020年中国研究生数学建模竞赛B题 降低汽油精制过程中的辛烷值损失模型 一 背景 汽油是小型车辆的主要燃料 汽油燃烧产生的尾气排放对大气环境有重要影响 为此 世界各国都制定了日益严格的汽油质量标准 见
  • linux 套接字文件类型,Linux下的文件类型

    Linux下的文件类型 1 开头 表示普通文件 2 d开头 表示目录文件 3 b开头 表示块设备 4 c开头 表示是字符设备 5 I开头 表示符号链接文件 6 p开头 表示管道文件pipe 7 s开头 表示套接字文件socket root
  • 浅谈BERT/Transformer模型的压缩与优化加速

    作者 姚益武 单位 阿里巴巴集团 研究方向 AI算法与工程架构 前言 BERT Transformer 结构及其变体 已成为自然语言处理 NLP 语音识别 ASR 等领域的主流序列建模结构 并且 相比于卷积操作的局部特征提取能力 以及平移不
  • 【Python】ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any

    一 问题描述 在使用Python的判断语句的时候 data2 data2 Month 11 and data2 Day 11 我的本意是想找出11月11日的数据 运用上面的代码 却得到了报错 报错信息 ValueError The trut
  • [QT编程系列-38]:数据存储 - SQLite数据库存储与操作

    目录 1 SQLite数据库概述 1 1 简介 1 2 SQLite不支持网络连接 1 3 SQLite不需要安装MySQL Server数据库 1 4 SQLite性能 1 5 SQLite支持的数据条目 2 SQLite操作示例 3 Q
  • 找不到插件 ‘org.springframework.boot:spring-boot-maven-plugin:‘问题

    出现pom文件找不到插件 org springframework boot spring boot maven plugin 问题 可能是因为版本没有绑定好 去一级父类依赖找对应的插件版本 在pom文件中加上 把父类的version加到po
  • 1小时学会CSS-下

    今天给大家分享的内容包含CSS 盒子模型 CSS 标准布局 CSS 浮动布局 并以案列进行详细说明 一 CSS 盒子模型 CSS 将所有元素都当成盒子 CSS布局其实就是如何堆放盒子 组成 content 内容 gt padding 内边距
  • 【c语言】小程序游戏——飞机游戏(二)

    在接下来 我们需要对飞机添加一些属性 1 利用键盘控制飞机的移动 2 按空格键可以发射激光 NO 1 利用键盘控制飞机的移动 首先我们需要了解的是 如果想要通过按键来控制飞机的移动 那么我们具体要怎么控制呢
  • Verilog(4)系统任务monitor,time,stop,random等,编译预处理语句

    调试用系统任务和常用编译预处理语句 用于调试和差错的系统任务 以及编写模块时的预处理语句 系统任务 monitor 提供了监控和输出参数列表中表达式或变量值的功能 参数列表中输出控制格式字符串和输出表列的规则和 d i s p l a
  • java基础之replace,replaceAll

    走在乡间的小路上 回首过往 以下代码结果都是显示在Console框中 所以 n会被解析成换行 n只显示 n 所以看到结果换行其实是输出了 n 看到输出 n 其实输出的是 n replace和replaceAll是编程中经常用到的替换函数 成
  • 求出1~N范围中所有的素数

    判断是否为素数 public static boolean isPrime int n int sqrt int Math sqrt n int i for i 2 i lt sqrt i if n i 0 break if i gt sq
  • 小程序瀑布流布局

    list wxml列表
  • Java的深浅拷贝机制

    Java的深浅拷贝机制 我们先理解一下深浅拷贝的概念 1 浅拷贝 Java在进行对象拷贝的过程中 对于他的成员变量进行拷贝 如果是基本数据类型 就会直接拷贝他的值 如果是引用类型 则会拷贝他的引用地址 而不会拷贝对象本身 2 深拷贝 Jav
  • Windows 10 和 Windows 11 有什么区别?

    Windows 10 和 Windows 11 有什么区别 Windows 11 具有 Windows 10 的全部功能和安全性 同时具有经重新设计而焕然一新的外观 它还自带一些新的工具 声音和应用 所有细节面面俱到 颜值 功能与安全性集于
  • Python字符串转为字典方法大全

    方法一 通过内置函数eval 1 2 3 4 5 6 7 8 9 10 11 12 13 str info name test age 18 dict info eval str info print string info type is