字典

team={}#创建字典
team['aaa']=1#往字典里添加元素
team['bbb']=2team.keys()
dict_keys(['aaa', 'bbb'])'aaa' in team.keys()
True
'la' in team.keys()
Falseteam.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查找
print("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/pythondict = {'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 indexingteam.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']=3print("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 3for 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']=3mate={}
mate['ccc']=4
mate['ddd']=5
team.update(mate)
#结果
>>>team
{'aaa': 1, 'bbb': 2, 'ccc': 4, 'ddd': 5}

排序

万能写法 python2 python3通用 对整个字典按key或value排序

#python2 python3通用,结果一样
team={}
team['bb']=3
team['cc']=1
team['aa']=2def 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) 反序带reversereturn 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]]=teamNoteaminfo[onePair[1]]=teamNoteam_strength_map[teamNo]=strength[onePair[0]]+strength[onePair[1]]teamNo=teamNo+1if 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就加上第一个人贡献的strengthif 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 字典操作 总结相关推荐

  1. python字典操作添加_Python字典常见操作实例小结【定义、添加、删除、遍历】

    本文实例总结了python字典常见操作.分享给大家供大家参考,具体如下: 简单的字典: 字典就是键值对key-value组合. #字典 键值对组合 alien_0 ={'color':'green', ...

  2. Python字典操作大全

    //2018.11.6 Python字典操作 1.对于python编程里面字典的定义有以下几种方法: >>> a = dict(one=1, two=2, three=3) > ...

  3. python 字典操作提取key,value

    http://blog.csdn.net/hhtnan/article/details/77164198 python 字典操作提取key,value dictionaryName[key] = va ...

  4. python字典操作题_python字典练习题

    python字典练习题 写代码:有如下字典按照要求实现每一个功能dict = {"k1":"v1","k2":"v2", ...

  5. python字典操作 遍历_Python字典遍历操作实例小结

    本文实例讲述了Python字典遍历操作.分享给大家供大家参考,具体如下: 1 遍历键值对 可以使用一个 for 循环以及方法 items() 来遍历这个字典的键值对. dict = {'evapora ...

  6. python字典操作技巧_python的字典使用方法大全

    字典是另一种可变容器模型,且可存储任意类型对象. 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 . 键一般是唯一的,如 ...

  7. python 字典操作遍历

    # 字典即为键值对集合.字典可以有若干个键值对,如果键重复的以后一个为实际值. dict = {"name": "LCF", "age": ...

  8. python字典调用_【python Dict】 python 字典操作

    python字典 是一个无序.以键值对存储的数据类型,数据关联性强.唯一一个映射数据类型.键:必须是可哈希(不可变的数据类型:字符串.数字.元组.bool)值,并且是唯一的 None: none 是一 ...

  9. python字典操作的方法_python 字典操作方法详解

    python 字典操作方法详解 一.总结 一句话总结: 字典就是键值对映射 ,像js和php中的键值对数组:{'name':'jamnes','age':'32'} 1.python字典的增删改查? ...

  10. python字典操作函数_【python】字典的操作方法和函数

    一.字典内置函数&方法 Python字典包含了以下内置函数: 1.cmp(dict1, dict2):比较两个字典元素. 2.len(dict):计算字典元素个数,即键的总数. 3.str(d ...

最新文章

  1. 246.三元图的应用与绘图实战
  2. matlab rebit,BIM的算法最新消息!MATLAB被禁也有BIM开源工具用!
  3. 后处理没有pui文件怎么打开_UG后处理添加具体步骤
  4. Flask第一篇——URL详解
  5. 语音识别学习日志 2019-7-15 语音识别基础知识准备4 {Baun-Welch算法}
  6. (63)SPI外设驱动分频模块(二)(第13天)
  7. python pillow环境_解决Python图片处理模块pillow使用中出现的问题
  8. 人人商城小程序服务器根目录,微擎通用-人人商城v3小程序安装步骤小程序配置说明...
  9. java实现复制文件目录及文件到指定路径下
  10. 同样的神经网络引擎,苹果A11芯片比华为麒麟970牛在哪?
  11. vue实现连接打印机功能
  12. C#学习笔记8 事件
  13. Coloring Contention
  14. 两张图片切换比例虚拟进度条
  15. 蓝桥杯2021年第十二届省赛-双向排序
  16. 苹果手机升级13无法开机_苹果11更新ios13.7卡在开机页面
  17. python爬虫---12306获取列车座位信息
  18. 设计模式初探-观察者模式
  19. 05 _ 经验总结:如何给你的代码起好名字?
  20. 关于北洋壳的网友问题

热门文章

  1. 大一学生《Web编程基础》期末网页制作 HTML+CSS+JavaScript 网页设计实例 企业网站制作
  2. 在vue中,如何处理手机物理键返回
  3. 服务器连接显示18456,SQL2008无法连接到服务器,用户’XX’登录失败(错误18456)解决方法...
  4. Linux文件管理-用户管理-磁盘管理
  5. java得出两段时间重叠的天数,以及日期
  6. unity3D打开Visual Studio编写代码没有代码补全怎么回事
  7. U盘安装CentOS7查看u盘设备名称的命令
  8. 2471. [EZOI 2016]源氏的数学课
  9. 为什么LR模型损失函数使用交叉熵不用均方差?
  10. 用 Python 绘制美丽的樱花