Home > Backend Development > Python Tutorial > Python中实现字符串类型与字典类型相互转换的方法

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

WBOY
Release: 2016-06-16 08:42:46
Original
1652 people have browsed it

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

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

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

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

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

Copy after login

二、字符串(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'}
>>>

Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template