Python 字典(Dictionary)
作者:互联网
一、字典
字典dict是无序的
字典的存储数据形式 key-value的数据形式
#dir()查看他的方法 data={"name":"lisi","age":20,"work":"测试开发工程师"} print(dir(data)) ''' 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] name '''
1 # clear清空 2 data={"name":"lisi","age":20,"work":"测试开发工程师"} 3 data.clear() 4 print(data)
1 #pop删除 并且返回删除的元素 2 data={"name":"lisi","age":20,"work":"测试开发工程师"} 3 print(data.pop("age")) 4 print(data)
1 # copy复制 2 data={"name":"lisi","age":20,"work":"测试开发工程师"} 3 data2=data.copy() 4 print(data2)
1 # update 合并 2 data={"name":"lisi","age":20,"work":"测试开发工程师"} 3 dict1={"sex":"女"} 4 data.update(dict1) 5 print(data)
data={"name":"lisi","age":20,"work":"测试开发工程师"} #获取所有的key for key in data.keys(): print(key) #获取所有的value for value in data.values(): print(value)
#获取key对应的具体的value data={"name":"lisi","age":20,"work":"测试开发工程师"} #获取名字 print(data.get("name")) print(data["name"]) #一般用第二种 #获取工作 print(data["work"])
1 #对字典进行循环 2 data={"name":"lisi","age":20,"work":"测试开发工程师"} 3 for key,value in data.items(): 4 print(key,":",value)
#需求:key=="age"并且value==20输出我今年20岁了 data={"name":"lisi","age":20,"work":"测试开发工程师"} for key,value in data.items(): if key=="age" and value==20: print("我今年20岁了")
二、字典案例实战
1.
1 data={ 2 "datas": [ 3 { 4 "author": "wuya", 5 "done": True, 6 "id": 1, 7 "name": "Python接口自动化测试实战" 8 }, 9 { 10 "author": "无涯", 11 "done": False, 12 "id": 2, 13 "name": "Selenium3自动化测试实战" 14 } 15 ], 16 "msg": "ok", 17 "status": 0 18 } 19 #需求:输出Python接口自动化测试实战 20 print(data["datas"][0]["name"]) 21 22 #需求:输出Selenium3自动化测试实战 23 print(data["datas"][1]["name"])
2.
1 data={"status":0, 2 "msg":"ok", 3 "datas":[ 4 {"name":"lisi","age":10},{"name":"god","age":20,"work":["test",{"language":"Python语言"}]} 5 ] 6 } 7 #需求:输出python语言 8 print(data["datas"][1]["work"][1]["language"])
3.
1 data={"status":0, 2 "msg":"ok", 3 "datas":[{"name":"lisi","age":10},{"name":"god","age":20,"work":["test",{"language":"Python语言","school":["北京大学",{"专业":"计算机科学与技术"}]}]}] 4 } 5 6 #输出计算机科学与技术 7 print(data["datas"][1]["work"][1]["school"][1]["专业"])
4.
1 data=["language",{"语言":["Go","Python","Java"]}] 2 # 输出结果是:Go,Python,Java 3 print(",".join(data[1]["语言"]))
5.
1 data1={"status":0,"datas":[{"name":"lisi","score":90}, 2 {"name":"wangmazi","score":88}, 3 {"name":"wangwu","score":60}, 4 {"name":"zhaosi","score":59}, 5 {"name":"zhaosi","score":29}]} 6 #需求,对学生成绩进行排序,从低到高排序 7 listscore=[] 8 for item in data1["datas"]: 9 listscore.append(item["score"]) 10 listscore.sort() 11 print(listscore)
6.
1 data2={"status":0,"datas":[ 2 {"name":"lisi","score":90}, 3 {"name":"wangmazi","score":88}, 4 {"name":"wangwu","score":60}, 5 {"name":"zhaosi","score":59} 6 ]} 7 #需求:输出lisi,wangmazi,wangwu,zhaosi 8 listname=[] 9 for item in data2["datas"]: 10 listname.append(item["name"]) 11 print(",".join(listname))
标签:20,name,Dictionary,Python,age,lisi,print,data,字典 来源: https://www.cnblogs.com/yingyingShare/p/15545459.html