一:python字典的增删改查
1、添加:加入键和值,即可新增,以下是新增了"f":"12ab"
dict = {
"a": "bbb",
"b": None,
"c": True,
"d": 13,
"e": ["13", "14"]
}
dict["f"] = "12ab" # 字典的新增
print(dict)
执行代码结果:
D:\Python36\python.exe D:/test/mingtest/case/bolg/test_19.py
{'a': 'bbb', 'b': None, 'c': True, 'd': 13, 'e': ['13', '14'], 'f': '12ab'}
Process finished with exit code 0
2、删除:可直接使用del方法,删除键,所对应的值也会删除
dict = {
"a": "bbb",
"b": None,
"c": True,
"d": 13,
"e": ["13", "14"]
}
del(dict["a"]) # 删除"a": "bbb"
print(dict)
执行代码结果:
D:\Python36\python.exe D:/test/mingtest/case/bolg/test_19.py
{'b': None, 'c': True, 'd': 13, 'e': ['13', '14']}
Process finished with exit code 0
3、修改:键不变,值改变
dict = {
"a": "bbb",
"b": None,
"c": True,
"d": 13,
"e": ["13", "14"]
}
dict["a"] = "fffff" # 修改"a"
print(dict)
执行代码结果:
D:\Python36\python.exe D:/test/mingtest/case/bolg/test_19.py
{'a': 'fffff', 'b': None, 'c': True, 'd': 13, 'e': ['13', '14']}
Process finished with exit code 0
4、查找:
dict = {
"a": "bbb",
"b": None,
"c": True,
"d": 13,
"e": ["13", "14"]
}
print(dict["b"]) # 直接print打印对应的键
执行代码结果:
D:\Python36\python.exe D:/test/mingtest/case/bolg/test_19.py
None
Process finished with exit code 0
二:字典转json,json转字典
1、字典转json:看注释
import json # 导入json这个库
dict = {
"a": "bbb",
"b": None,
"c": True,
"d": 13,
"e": ["13", "14"]
}
print(type(dict)) # 打印dict数据什么数据类型?结果显示为python字典
js = json.dumps(dict) # 使用dumps这个方法对字典转换为json格式
print(js)
print(type(js)) # 打印js的数据类型,属于字符串,说明转换成功,None显示为null,True显示为小写
执行代码结果:
D:\Python36\python.exe D:/test/mingtest/case/bolg/test_19.py
{"a": "bbb", "b": null, "c": true, "d": 13, "e": ["13", "14"]}
Process finished with exit code 0
2、json转字典:看注释
import json # 导入json这个库
dict = {
"a": "bbb",
"b": None,
"c": True,
"d": 13,
"e": ["13", "14"]
}
print(type(dict)) # 打印dict数据什么数据类型?结果显示为python字典
js = json.dumps(dict) # 使用dumps这个方法对字典转换为json格式
print(js)
print(type(js)) # 打印js的数据类型,属于字符串,说明转换成功,None显示为null,True显示为小写
dict1 = json.loads(js) # 使用loads这个方法对json转换成字典
print(dict1) # 打印dict1,运行结果,null显示为None,true显示为大写
print(type(dict1)) # 打印结果显示dict1显示为字典数据类型
执行代码结果:
D:\Python36\python.exe D:/test/mingtest/case/bolg/test_19.py
{"a": "bbb", "b": null, "c": true, "d": 13, "e": ["13", "14"]}
{'a': 'bbb', 'b': None, 'c': True, 'd': 13, 'e': ['13', '14']}
Process finished with exit code 0