【Python】字典的使用及相关函数
字典是另一种可变容器模型,且可存储任意类型对象
向空字段添加数据
d = {} d["name"] = "zhangsan" print(d) 》》》运行结果 {'name': 'zhangsan'} 进程已结束,退出代码为 0
将列表数据写入字段中
1、部分数值
d ={} a = ['a','b','c','d','e'] b = ['11','22','33','44','55'] for i in range(3): d[a[i]] = b[i] print(d)
{'a': '11', 'b': '22', 'c': '33'} 进程已结束,退出代码为 0
2、部分数值
d ={} a = ['1','2','3','4','5'] b = ['11','22','33','44','55'] for i in range(2,4]: d[a[i]] = b[i] print(d)
{'3': '33', '4': '44'} 进程已结束,退出代码为 0
3、 全部数值
d ={} a = ['1','2','3','4','5'] b = ['11','22','33','44','55'] for i in range(len(a)): d[a[i]] = b[i] print(d)
{'1': '11', '2': '22', '3': '33', '4': '44', '5': '55'} 进程已结束,退出代码为 0
读取字典值
d = {} d["name"] = "zhangsan" d["age"] = "18" print(d) print(d["name"])
{'name': 'zhangsan', 'age': '18'} zhangsan 进程已结束,退出代码为 0
修改字典值
d = {} d["name"] = "zhangsan" d["age"] = "18" print(d) print(d["name"]) d["name"] = "zhangsan2" print(d)
{'name': 'zhangsan', 'age': '18'} zhangsan {'name': 'zhangsan2', 'age': '18'} 进程已结束,退出代码为 0
删除字典
d = {} d["name"] = "zhangsan" d["age"] = "18" print(d) print(d["name"]) d["name"] = "zhangsan2" print("修改 key value",d) del d["age"] print("删除key-age",d) d.clear() print("清空字典",d)
{'name': 'zhangsan', 'age': '18'} zhangsan 修改 key value {'name': 'zhangsan2', 'age': '18'} 删除key-age {'name': 'zhangsan2'} 清空字典 {} 进程已结束,退出代码为 0
# del d 删除字典,字典将会不存在,输出d 时提示异常
dict.items()
以列表返回可遍历的(键, 值) 元组数组。
d ={} a = ['a','b','c','d','e'] b = ['11','22','33','44','55'] for i in range(len(a)): d[a[i]] = b[i] print(d) print(d.items()) for key,value in d.items(): print(key,value) di = {key:value for key,value in d.items() if key in a} print(di) de = [{key:value for key,value in d.items() if key in b}] print(de)
{'a': '11', 'b': '22', 'c': '33', 'd': '44', 'e': '55'} dict_items([('a', '11'), ('b', '22'), ('c', '33'), ('d', '44'), ('e', '55')]) a 11 b 22 c 33 d 44 e 55 {'a': '11', 'b': '22', 'c': '33', 'd': '44', 'e': '55'} [{}] 进程已结束,退出代码为 0
-------------------------------------------------------------------------------------
如果万事开头难 那请结局一定圆满 @ Phoenixy
-------------------------------------------------------------------------------------