字典dict是无序的key:value格式的数据序列
#coding:utf-8 #/usr/bin/python """ 2018-11-11 dinghanhua 字典 """ ‘‘‘dict 无序的key:value组合 key要是不可变类型,如数字、字符串、元组 key不可重复,重复的会被最后一个覆盖 ‘‘‘ dict_id = {‘1‘:‘python‘,‘2‘:‘java‘,‘3‘:‘javascript‘,‘4‘:‘go‘,‘2‘:‘JAVA‘} print(dict_id)
‘‘‘查询、新增、修改、删除数据,长度len()‘‘‘ print(‘dict包含的键值对个数:‘,len(dict_id)) print(‘取值dict[key]‘,dict_id[‘1‘])#查询 print(‘取值dict.get(key,default)‘,dict_id.get(‘1‘,‘no key‘),dict_id.get(‘11‘,‘no key‘)) #存在key取value,不存在取默认值 print(‘是否存在key‘,‘2‘ in dict_id) # key in dict #print(‘key不存在,报keyerror错误:‘,dict_id[‘6‘]) dict_id[‘2‘] = ‘java2‘ #更新数据 print(dict_id) dict_id[‘5‘] = ‘php‘ #新增数据 print(dict_id) del dict_id[‘5‘] #删除数据 print(dict_id) dict_id[‘5‘] = ‘test‘ print(dict_id) popele = dict_id.pop(‘5‘) print(‘popele=%s,dict is %s‘%(popele,dict_id))
‘‘‘查看所有的key,value‘‘‘ for k in dict_id: print(k,end=‘ ‘) print(dict_id[k]) #只取keys print(dict_id.keys()) #只取values print(dict_id.values()) #取key,value print(dict_id.items()) for k,v in dict_id.items(): print(k,v)
‘‘‘用序列list、tuple、set生成dict的key‘‘‘ li = [‘dog‘,‘cat‘,‘dinosaur‘] dict_li = {} dict_li = dict_li.fromkeys(li) print(dict_li) ss = {‘dog‘,‘cat‘,‘pig‘} dict_li2 = dict_li.fromkeys(ss,‘1‘) #第二个参数是默认的value值 print(dict_li2) ‘‘‘dict合并‘‘‘ dict_li.update(dict_li2) # dict2的添加到dict1中 print(dict_li)
‘‘‘排序 sorted‘‘‘ print(‘排序:‘,sorted(dict_id)) #默认按键排序 li = sorted(dict_id.values()) #values排序 print(li) li = sorted(dict_id.items()) #key,value默认按key排序 print(li) li = sorted(dict_id.items(),key=lambda item:item[1]) #按value排序 print(li)
‘‘‘练习:将cookie字符串改成dict‘‘‘ cookie = ‘_ga=GA1.2.1595072447.1537137596; _gid=GA1.2.1806558744.1541837860; ‘ ‘Hm_lvt_3eec0b7da6548cf07db3bc477ea905ee=1541250960,1541292056,1541837859,1541861084; ‘ ‘Hm_lpvt_3eec0b7da6548cf07db3bc477ea905ee=1541900415‘ dict_cookie = {} cookies = cookie.split(‘;‘) for c in cookies: cl = c.split(‘=‘) dict_cookie[cl[0]] = cl[1] print(dict_cookie)
‘‘‘练习:测试报告字符串格式化‘‘‘ template = """ <html> <head> <title>%(title)s</title> </head> <body> <h1>%(head)s</h1> <p>%(para1)s</p> </body> </html> """ dict_report = {‘title‘:‘testreport‘,‘head‘:‘xx项目测试报告‘,‘para1‘:‘该测试报告包含以下几部分。。。‘} print(template%dict_report)
‘‘‘练习:去除dict的value重复项,保留其中一个‘‘‘ cookie = {‘_ga‘: ‘GA1.2.1595072447.1537137596‘, ‘ _gid‘: ‘GA1.2.1806558744.1541837860‘, ‘ Hm_lvt_3eec0b7da6548cf07db3bc477ea905ee‘: ‘1541250960,1541292056,1541837859,1541861084‘, ‘ _gid2‘: ‘GA1.2.1806558744.1541837860‘, ‘ Hm_lpvt_3eec0b7da6548cf07db3bc477ea905ee‘: ‘1541900415‘} # 定义一个新的字典,如果value不在新的dict.values里,则插入 dict_new = {} for key,value in cookie.items(): if value not in dict_new.values(): dict_new[key] = value print(‘替换后:‘,dict_new) #利用dict的key自动去重 dict_new2 = {} for key,value in cookie.items(): dict_new2[value] = key print(‘key和value对调之后已去重‘,dict_new2) for key,value in dict_new2.items(): dict_new2[value] = key dict_new2.pop(key) print(‘再恢复key value对应关系‘,dict_new2) # 取所有的values值,个数大于1,则删除 dict_new = cookie.copy() for key,value in cookie.items(): if list(dict_new.values()).count(value) >1: del dict_new[key] print(dict_new)
‘‘‘dict记录了成绩,计算平均分,最高分等‘‘‘ #只记录了一科成绩,算平均分,最高分的人 dic_data = {‘aaa‘:70,‘bbb‘:95,‘ccc‘:95,‘ddd‘:85} li_score = dic_data.values() print(‘平均分:‘,sum(li_score)/len(li_score)) #平均分 maxscore = max(dic_data.values()) #最高分 for key,value in dic_data.items(): if value == maxscore: print(‘No1 is %s‘%key) #按分数排序,取第一个人名和最高分,不适合第一名有多个的 print(sorted(dic_data.items(),key = lambda x:x[1],reverse=True)[0]) #记录了3个科目的成绩,计算每个人的平均分,找到均分不及格的人;每个科目的平均分和最高分,每科的第一名 dic_data = {‘aaa‘:[60,60,50],‘bbb‘:[90,60,80],‘ccc‘:[90,95,98],‘ddd‘:[88,85,97]} #计算每个人的平均分,value的平均分 for key,value in dic_data.items(): avg = sum(value)/len(value) print(‘%s 的平均分是 %.2f‘%(key,avg)) if avg < 60: print(‘均分不及格‘) #计算各科的平均分和最高分 取value[i]的均分和最高 avglist = [] maxlist = [] lendic = len(dic_data) for i in range(0,3): li_score = [ value[i] for value in dic_data.values()] #取出每个科目的所有人的成绩列表 avglist.append(sum(li_score)/lendic) #平均分 maxlist.append(max(li_score)) #最高分 print(‘各科目平均分:‘,avglist) print(‘各科目最高分:‘,maxlist) print(list(zip([‘语文‘,‘数学‘,‘英语‘],avglist,maxlist))) #找最高分的学生 for key,value in dic_data.items(): for i in range(0,3): if value[i] == maxlist[i]: print(‘第%s个科目的最高分学生%s‘%(i+1,key)) #排序 for i in range(0,3): print(sorted(dic_data.items(),key = lambda x:x[1][i],reverse=True)) #各科目成绩倒序排
‘‘‘计算每个人的平均分; 科目的均分和最高分,及拿到最高分的人‘‘‘ dic_data = {‘aaa‘:{‘语文‘: 60, ‘数学‘: 60, ‘英语‘: 50}, ‘bbb‘:{‘语文‘: 90, ‘数学‘: 60, ‘英语‘: 80}, ‘ccc‘:{‘语文‘: 90, ‘数学‘: 95, ‘英语‘: 98}, ‘ddd‘:{‘语文‘: 88, ‘数学‘: 85, ‘英语‘: 97}} #每个人的平均分 for key,value in dic_data.items(): avgscore = sum(value.values())/len(value.values()) #平均分 print(‘%s的平均分是%.2f‘%(key,avgscore)) if avgscore < 60: print(‘均分不及格‘) #科目最高分,均分 dict_course = {‘语文‘:None,‘数学‘:None,‘英语‘:None} for key in dict_course: li_score = [ value[key] for value in dic_data.values()] print(key,li_score) print(‘%s平均分:%.2f‘%(key,sum(li_score)/len(li_score))) print(‘%s最大值:%.2f‘%(key,max(li_score))) #得分最高的 for name,score in dic_data.items(): if score[key] == max(li_score): print(‘科目%s得分最高的是%s‘%(key,name))
the end!
原文地址:https://www.cnblogs.com/dinghanhua/p/9942821.html
时间: 2024-10-07 06:32:35