字典的定义
infos = {'name':'张晓红','sex':'女','address':'上海','age':18}
1 stus = {"name":"张三","sex":"女"} 2 print(list(stus.values())) #结果输出:['女', '张三'] 3 print(list(stus.keys())) #结果输出:['sex', 'name'] 4 print(list(stus.items())) #结果输出:[('sex', '女'), ('name', '张三')]
字典实现账号注册
1 stus = {"name":"张三"} 2 stus.update({"sex": "男"}) 3 print(stus) #结果输出:{'name': '张三', 'sex': '男'} 4 stus.update({"sex":"女"}) 5 print(stus) #结果输出:{'name': '张三', 'sex': '女'}
1 d = {'a':68,'w':62,'c':91,'d':83,'e':93,'f':89,'g':67} 2 print(list(d.items())) #结果输出:[('w', 62), ('a', 68), ('f', 89), ('c', 91), ('g', 67), ('d', 83), ('e', 93)] 3 d2 = sorted(d.items(),key=lambda x:x[1]) #lambda x:x[1] 根据字典的value排序,lambda x:x[0] 根据字典的key排序 4 print(d2) #结果输出:[('w', 62), ('g', 67), ('a', 68), ('d', 83), ('f', 89), ('c', 91), ('e', 93)] 5 print(d2[:2]) #结果输出:[('w', 62), ('g', 67)] 6 7 d3 = sorted(d.items(),key=lambda x:x[1],reverse=True) 8 print(d3) #结果输出:[('e', 93), ('c', 91), ('f', 89), ('d', 83), ('a', 68), ('g', 67), ('w', 62)] 9 print(d3[:2]) #结果输出:[('e', 93), ('c', 91)]