在工作中遇到一个小问题,需要将一个
Python
的字符串转为字典,比如字符串:
user_info = '{"name" : "john", "gender" : "male", "age": 28}'
我们想把它转为下面的字典:
user_dict = {"name" : "john", "gender" : "male", "age": 28}
有以下几种方法:
>>> import json
>>> user_info= '{"name" : "john", "gender" : "male", "age": 28}'
>>> user_dict = json.loads(user_info)
>>> user_dict
{u'gender': u'male', u'age': 28, u'name': u'john'}
但是使用 json
进行转换存在一个潜在的问题。
由于 json
语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号。
(官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此下面的转换是错误的:
>>> import json
>>> user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
>>> user_dict = json.loads(user_info)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
>>> user_info = '{"name" : "john", "gender" : "male", "age": 28}'
>>> user_dict = eval(user_info)
>>> user_dict
{'gender': 'male', 'age': 28, 'name': 'john'}
>>> user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
>>> user_dict = eval(user_info)
>>> user_dict
{'gender': 'male', 'age': 28, 'name': 'john'}
通过 eval
进行转换就不存在上面使用 json
进行转换的问题。但是,使用 eval
却存在安全性的问题
,比如下面的例子:
>>> user_info = raw_input('input user info: ')
>>> user_dict = eval(user_info)
>>> user_dict = eval(user_info)
>>> import ast
>>> user = '{"name" : "john", "gender" : "male", "age": 28}'
>>> user_dict = ast.literal_eval(user)
>>> user_dict
{'gender': 'male', 'age': 28, 'name': 'john'}
>>> user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
>>> user_dict = ast.literal_eval(user)
>>> user_dict
{'gender': 'male', 'age': 28, 'name': 'john'}
使用 ast.literal_eval
进行转换既不存在使用 json
进行转换的问题,也不存在使用 eval
进行转换的 安全性问题
,因此推荐使用 ast.literal_eval
。
引言在工作中遇到一个小问题,需要将一个 Python 的字符串转为字典,比如字符串:user_info = '{"name" : "john", "gender" : "male", "age": 28}'我们想把它转为下面的字典:user_dict = {"name" : "john", "gender" : "male", "age": 28}有以下几种方法:1. 通过 jso......
dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }
//这是javascript中的一个JSON对象
json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str',
s=”name=lyy&age=3&sex=women&boyfriend=czt”
2、需要再对s1进行拆分,此时s1只有4个元素,对s1进行遍历,拿到类似“name=lyy”的字符串,即s2
3、同样通过分割把s2分割成s3列表
4、s3为[name,lyy],即为字典的键和值赋值,键=s3[0],值=s3[1]
代码如下:
# -*- coding: utf-8 -*-
s=name=lyy&age=3&sex=women&boyfriend=czt\nd=
字典格式化字符串时,在转换说明符中的%字符后面加上键值,并用括号括起来,后面在跟上其他说明元素。只要所加上的键值可以在字典中找到,就可以获得任意数量得转换说明符。
>>> x = {'name':'jack','age':'12','addr':'river road 12th'}
>>> print ("%s 's age is %s" %x)
>>> print ("%(name)s 's ag
前面章节介绍过,在格式化字符串时,如果要格式化的字符串模板中包含多个变量,后面就需要按顺序给出多个变量,这种方式对于字符串模板中包含少量变量的情形是合适的,但如果字符串模板中包含大量变量,这种按顺序提供变量的方式则有些不合适。
这时,就可以使用字典对字符串进行格式化输出,具体方法是:在字符串模板中按 key 指定变量,然后通过字典为字符串模板中的 key 设置值。
例如如下程序:
# 字符串模...
6.2.3 字典的格式化字符串
在5.2.1节讲过使用百分号(%)配合元组对字符串进行格式化的方式。在字符串中使用%s、%d等格式表示要替换的值,这个字符串可以成为模板,然后用字符串模板与元组通过%进行格式化。
'xyz %d abc %s' % (20,'OK')
如果使用字典对字符串进行格式化,要比使用元组更酷。因为在字符串模板中可以用命名的方式指定格式化参数。在Python2.x中,仍然可...
for key, value in d.items():
if isinstance(value, str):
d[key] = value.replace("'", "") # 去掉单引号
print(d) # 输出 {'name': 'John', 'age': 30}
这里使用 isinstance() 函数来判断字典中的值是否为字符串类型,如果是字符串类型就使用 replace() 方法将单引号替换为空字符串。注意,这里直接修改了原字典的值,如果不想修改原字典可以创建一个新的字典来保存去掉单引号后的字符串。
docker load 出错 open /var/lib/docker/tmp/docker-import-837327978/bin/json: no such file or directory
25680
Kubernetes 实战(02)— 使用 Deployment、Service、Nginx Ingress Controller 搭建 MariaDB+Nginx+WordPress
Kubernetes 实战(01)— 使用 ConfigMap、Pod搭建 MariaDB+Nginx+WordPress
docker/docker-compose 部署 nginx+mysql+wordpress 实战