Python 字典操作 总结
2018-04-04 10:38
369 查看
字典
增
team={}#创建字典 team['aaa']=1#往字典里添加元素 team['bbb']=2 team.keys() dict_keys(['aaa', 'bbb']) 'aaa' in team.keys() True 'la' in team.keys() False team.values() dict_values([1, 2]) 3 in team.values() False 2 in team.values() True
删
>>>team.pop('aaa')#删除指定key的键值对,返回对应的值,这是在命令行里的写法,不在命令行里想获取pop弹出的值可见片段2 1 >>>team {'bbb': 2} >>>team['ccc']=3 >>>team {'bbb': 2, 'ccc': 3} >>>team.clear()#把所有键值对都删除 >>>team {}
#片段2: team={} team['aaa']=1 team['bbb']=2 temp=team.pop('aaa') >>>team {'bbb': 2} >>>temp 1
改
team={} team['aaa']=1 team['bbb']=2 print(team) team['bbb']='ccc'#直接这样改就好了 print("After modify",team) 输出: {'aaa': 1, 'bbb': 2} After modify {'aaa': 1, 'bbb': 'ccc'}
查
按key查
team={} team['aaa']=1 team['bbb']=2 #按key查 .get()的用法 avalue=team.get('aaa')#按照key查找 p 4000 rint("avalue is",avalue) print("type of avalue is",type(avalue)) cvalue=team.get('c')#如果没有这个key,返回的是None print("cvalue is",cvalue) print("type of cvalue is",type(cvalue)) print(cvalue is None) #结果如下: avalue is 1 type of avalue is <class 'int'> cvalue is None type of cvalue is <class 'NoneType'> True #setdefault的用法:按key查找并返回对应的value,如果key存在,返回对应值;如果key不存在,创建对应的key-value(value是None) 这也是和.get()方法不同的地方 print(team.setdefault('aaa'))#直接这样写 print(team) print(team.setdefault('eee')) print(team) #结果如下: 1 {'aaa': 1, 'bbb': 2} None {'aaa': 1, 'bbb': 2, 'eee': None} #按key查,python2里.has_key()的用法 #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.has_key('Age') print "Value : %s" % dict.has_key('Sex') #输出为 Value : True Value : False #按key查,python3里.__contains__() dict3 = {'name':'z','Age':7,'class':'First'}; print("Value : ",dict3.__contains__('name')) print("Value : ",dict3.__contains__('sex')) #输出结果 Value : True Value : False #按key查,.keys()是不能被下标索引的 >>>team.keys() dict_keys(['aaa', 'bbb', 'ccc']) type(team.keys()) <class 'dict_keys'> team.keys()[0] Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'dict_keys' object does not support indexing team.keys() dict_keys(['aaa', 'bbb', 'ccc']) 'aaa' in team.keys() True 'aaa ' in team.keys() False 'b' in team.keys() False
按value查
team.values() dict_values([1, 2, 3]) 1 in team.values() True '1' in team.values() False
遍历 .items() 旧貌新颜
在Python2.x中,items( )用于 返回一个字典的拷贝列表【Returns a copy of the list of all items (key/value pairs) in D】,占额外的内存。iteritems() 用于返回本身字典列表操作后的迭代【Returns an iterator on all items(key/value pairs) in D】,不占用额外的内存。
# -*- coding: UTF-8 -*- #Python2 a={'aaa':1,'bbb':2} print a.keys() #['aaa', 'bbb'] print a.items()#[('aaa', 1), ('bbb', 2)] print type(a.items())#<type 'list'> print a.iteritems()#<dictionary-itemiterator object at 0x7f325524d940> print type(a.iteritems())#<type 'dictionary-itemiterator'> print '-------------------------------' for k,v in a.iteritems(): print k,v ------------------------------- #aaa 1 #bbb 2 for k,v in a.items(): #Python2和Python3公用的遍历用万能写法 print k,v #aaa 1 #bbb 2
#!/usr/bin/python #Python3 a={'aaa':1,'bbb':2} print (a.keys())#dict_keys(['aaa', 'bbb']) print(type(a.keys()))#<class 'dict_keys'> print (a.items())#dict_items([('aaa', 1), ('bbb', 2)]) print (type(a.items()))#<class 'dict_items'> print (a.iteritems())#语法错误,python3就没有iteritems() print (type(a.iteritems())) print ('-------------------------------') for k,v in a.iteritems():#Python2和Python3公用的遍历用万能写法 print (k,v) #aaa 1 #bbb 2
Python 3.x 里面,iteritems() 和 viewitems() 这两个方法都已经废除了,而 items() 得到的结果是和 2.x 里面 viewitems() 一致的。在3.x 里 用 items()替换iteritems() ,可以用于 for 来循环遍历。
team={} team['aaa']=1 team['bbb']=2 team['ccc']=3 print("team.items type is ",type(team.items())) for i in team.items(): print(i) print(type(i)) print("----------------------------------") for i in team.items(): print ("key is ",i[0],"value is",i[1]) print("----------------------------------") for i,j in team.items(): print ("key is ",i,"value is",j) #结果: team.items type is <class 'dict_items'> ('aaa', 1) <class 'tuple'> ('bbb', 2) <class 'tuple'> ('ccc', 3) <class 'tuple'> ---------------------------------- key is aaa value is 1 key is bbb value is 2 key is ccc value is 3 ---------------------------------- key is aaa value is 1 key is bbb value is 2 key is ccc value is 3 for key in team.__iter__(): print (key) #结果 aaa bbb ccc >>>type(team.__iter__()) <class 'dict_keyiterator'> python3里好像没有iteritems(),iterkeys(),itervalues()了 #只遍历key或者只遍历value >>>type(team.keys()) <class 'dict_keys'> >>>team.keys() dict_keys(['aaa', 'bbb', 'ccc']) >>>type(team.values()) <class 'dict_values'> >>>team.values() dict_values([1, 2, 3]) for i in team.values(): print (i) 1 2 3
以另一个字典来更新当前字典:永结同心
team={} team['aaa']=1 team['bbb']=2 team['ccc']=3 mate={} mate['ccc']=4 mate['ddd']=5 team.update(mate) #结果 >>>team {'aaa': 1, 'bbb': 2, 'ccc': 4, 'ddd': 5}
排序
万能写法 python2 python3通用 对整个字典按key或value排序
#python2 python3通用,结果一样 te ba5e am={} team['bb']=3 team['cc']=1 team['aa']=2 def sortedDictValues1(adict): a=sorted(adict.items(), key=lambda d: d[0])#d[1]是根据value排序,d[0]是根据key排序 # a=sorted(adict.items(), key=lambda d: d[0],reverse=True) 反序带reverse return a print(team) temp=sortedDictValues1(team) print(temp) print(team) #结果 {'bb': 3, 'cc': 1, 'aa': 2} [('aa', 2), ('bb', 3), ('cc', 1)] {'bb': 3, 'cc': 1, 'aa': 2}
对key排序 sorted(),不修改原字典
#python3 #!/usr/bin/python team={} team['bb']=3 team['cc']=1 team['aa']=2 print(team) print(sorted(team.keys())) print(team) print(sorted(team.values())) print(team) {'bb': 3, 'cc': 1, 'aa': 2} ['aa', 'bb', 'cc'] {'bb': 3, 'cc': 1, 'aa': 2} [1, 2, 3] {'bb': 3, 'cc': 1, 'aa': 2}
例题 微软2019实习生笔试第四题
题目意思是一共有numOfKids那么多小朋友,每个小朋友有一个编号,从0开始编,每个小朋友还有一个力量值
有个箱子里面有cardDrawn那么多张卡片
每张卡片上有两个数,代表两个小朋友的编号,一张卡片上的两个小朋友就分到一队
如果没有被卡片抽到的小朋友,就自成一队
求所有队伍里力量值最大的一队
numOfKids=6 cardDrawn=3 teamPair=[[1,2],[2,3],[4,5]] strength=[11,2,3,15,8,22] def func(numOfKids,cardDrawn,teamPair,strength): teaminfo = {} # {1: 0, 2: 0, 3: 0, 4: 1, 5: 1} #记录每个人 与 其所在队伍号 team_strength_map = {} # 记录了每个队伍的队伍号,与该队伍成员的strength和 的对应关系 teamNo=0#初始化队伍号,从0开始 for onePair in teamPair: print(onePair) FirstPerson=teaminfo.setdefault(onePair[0]) SecondPerson=teaminfo.setdefault(onePair[1]) if FirstPerson is None and SecondPerson is None:#如果两个人都没被分组,那么为该二人新建一个队伍号 print("Double None") teaminfo[onePair[0]]=teamNo teaminfo[onePair[1]]=teamNo team_strength_map[teamNo]=strength[onePair[0]]+strength[onePair[1]] teamNo=teamNo+1 if FirstPerson is None and SecondPerson is not None:#如果第一个人还没分组 print("First None") teaminfo[onePair[0]]=teaminfo[onePair[1]]#把第二个人的组赋给第一个人的组 team_strength_map[teaminfo[onePair[1]]] += strength[onePair[0]]#第二个人所在组的strength就加上第一个人贡献的strength if SecondPerson is None and FirstPerson is not None:#如果第二个人还没分组 print("Second None") teaminfo[onePair[1]]=teaminfo[onePair[0]]#把第一个人的组赋给第二个人的组 team_strength_map[teaminfo[onePair[0]]] += strength[onePair[1]]#第一个人所在组的strength就加上第二个人贡献的strength #print(teaminfo) #print(team_strength_map) tempMax=max(team_strength_map.values()) for i in range(0,numOfKids):#遍历所有小朋友,寻找可怜的没有被分到组的小朋友非常有力量,可能是实际上的最大值 if i not in teaminfo.keys(): if strength[i]>tempMax: tempMax=strength[i] print("FinalStrengthMax is",tempMax) return tempMax result=func(numOfKids,cardDrawn,teamPair,strength)
相关文章推荐
- Python进阶篇之字典操作总结
- Python培训知识总结系列- 第二章Python数据结构第四部分-字典操作
- python字典基本操作总结
- Python字典与集合操作总结
- Python字典与集合操作总结
- python字典操作总结
- python dict字典操作用法详细总结
- Python:字典操作总结
- Python 元组、字典、集合操作总结
- python字典的创建方法总结及操作
- Python字典操作简明总结
- Python字典与集合操作总结
- Python进阶篇之字典操作总结
- [python]pythonic的字典常用操作
- python 文件操作总结
- Python学习总结之四 -- 这就是Python的字典
- Python数据类型中的字典-创建和基本操作
- python入门(四)-- 列表、元组、字典具体操作
- python-字典操作
- python 字典基础操作