python之json和dick数据类型
Python常见数据类型:None,bool,int,float,str,list,tuple,dict
# coding:utf-8
a = None # None
print(a)
b = False # bool
print(b)
c, d = 12, 10.6 # int,float
print(c)
print(d)
e = "12aad" # str, unicode
print(e)
f = [1, 10.4, "1232aas", "ad"] # list
print(f)
g = (1, 10.4, "1232aas", "ad") # tuple
print(g)
h = {"a": None,
"b": 12, "c": "ad", "d": [1, "ad", True],"f": {"aa": 11, "dd": False, "cc": ("1", 11)}}# dict
print(h)
print(type(h))# 查看数据类型用type函数
print(type(g))
容易忘记的集合set
Dict常用操作:增 删 改 查
# coding:utf-8# 字典的添加、删除、修改操作
d1 = {"a": None, "b": 1, "c": "12a", "d": True, "e": ["1", 12]}
d1["f"] = "abb" # 增print(d1)
del(d1["a"]) # 删print(d1)
d1["b"] = 15 # 改print(d1)
print(d1["e"]) # 查
print(d1.get("e")) # get方法查询不会报错
Dict遍历与更新
a = {"name": "koko",
"mail": "123@qq.com",
"age": "22",
"tel": "12345678901"}
print(a.values()) # dict_values(['koko', '123@qq.com', '22', '12345678901'])
print(a.keys()) # dict_keys(['name', 'mail', 'age','tel'])
print(a.items()) # dict_items([('name', 'koko'), ('mail', '123@qq.com'), ('age', '22'), ('tel', '12345678901')])
for key, value in a.items():# 字典遍历取值
print(key, value)
d = {"token": "xxxxxx","sign": "aaaaaaaaa"}
a.update(d)# 更新到字典a上
print(a) # {'name': 'koko', 'mail': '123@qq.com', 'age': '22', 'tel': '12345678901', 'token': 'xxxxxx', 'sign': 'aaaaaaaaa'}
dict转Json和json转dick
# coding:utf-8
import json
d1 = {"a": None,"b": False,"c": True,"d": "BAB2","e": ["1", 12],"f": ("1n", 90),"g": {"h": 1,"i": "11", "j": True}}
print(type(d1))
js = json.dumps(d1)#dick转json
df = json.loads(js)#json转dick
print(type(df))
print(type(js))
print(js)
字符串、字典、json傻傻分不清楚
# coding:utf-8
# 这里a是字典
a = {"a": True, "b": "bbb"}
# 这里b是字符串str
b = '{"a": True, "b": "bbb"}'
# c是list
c = [{"a": True, "b": "bbb"}]
# d是json ,也是字符串
d = '{"a": true, "b": "bbb"}'
字典和字符串转换
# 这里a是字典
a = {"a": True, "b": "bbb"}
# 字典转字符串
aa = str(a)
print(type(aa))
print(aa)
# 这里b是字符串str
b = '{"a": True, "b": "bbb"}'
# 字符串转字典
bb = eval(b)
print(type(bb))
print(bb)