Python中实现字符串类型与字典类型相互转换的方法

yipeiwu_com6年前Python基础

本文以实例形式简述了Python中字符串类型与字典类型相互转换的方法,是比较实用的功能。具体方法如下:

一、字典(dict)转为字符串(string)

我们可以比较容易的将字典(dict)类型转为字符串(string)类型。

通过遍历dict中的所有元素就可以实现字典到字符串的转换:

for key, value in sample_dic.items():
  print "\"%s\":\"%s\"" % (key, value)

二、字符串(string)转为字典(dict)

如何将一个字符串(string)转为字典(dict)呢?

其实也很简单,只要用 eval()或exec() 函数就可以实现了。

>>> a = "{'a': 'hi', 'b': 'there'}"
>>> b = eval(a)
>>> b
{'a': 'hi', 'b': 'there'}
>>> exec ("c=" + a)
>>> c
{'a': 'hi', 'b': 'there'}
>>>

感兴趣的朋友可以调试运行本实例,以加深对程序代码的理解。

相关文章

Python实现随机取一个矩阵数组的某几行

废话不多说了,直接上代码吧! import numpy as np array = np.array([0, 0]) for i in range(10): array =...

详解Python中内置的NotImplemented类型的用法

它是什么?   >>> type(NotImplemented) <type 'NotImplementedType'> NotImpl...

Linux(Redhat)安装python3.6虚拟环境(推荐)

python是3.6 centos 6 64位 1.安装python 2.安装pip wget https://bootstrap.pypa.io/get-pip.py --no-c...

Python中解析JSON并同时进行自定义编码处理实例

在对文件内容或字符串进行JSON反序列化(deserialize)时,由于原始内容编码问题,可能需要对反序列化后的内容进行编码处理(如将unicode对象转换为str)。 在Python...

python对常见数据类型的遍历解析

字符串遍历 >>> a_str = "hello itcast" >>> for char in a_str: ... print(char,...