标签:访问和遍历
一、访问某个元素1)访问某一个value
2)setdefault
3)get
例如:
dic01 = {95001: 56, 95004: 89, 95003: 98, 95002: 65}
print(dic01[95001])
# 如果给出的key不存在,怎么办?
# print(dic01[95088]) 出现异常!
# 解决办法:setdefault,get
print(dic01.setdefault(95088, "None"))
print(dic01.get(95088, "None"))
# 解释:使用setdefault和get是避免获取某一个key不出存在时的初始值
print(dic01.pop(95033, "None"))
# 解释:使用pop后面的参数是避免获取某一个key不出存在时的初始值
执行结果:
C:\python\python.exe C:/python/demo/file3.py
56
None
None
None
Process finished with exit code 0
二、如何遍历
1)标准的遍历
for i in dic01:
print(i, ":", dic01[i])
执行结果:
C:\python\python.exe C:/python/demo/file3.py
95001 : 56
95004 : 89
95003 : 98
95002 : 65
95088 : None
Process finished with exit code 0
三、三种重要的关键字
1)使用items来遍历,通过字典集合返回item:95001:56
dic01 = {95001: 56, 95004: 89, 95003: 98, 95002: 65}
print(dic01.items())
print(list(dic01.items())[0])
print("===================================")
list01 = list(dic01.items())
for i in list01:
print(list(i)[0], list(i)[1])
2)使用keys来遍历,key:95001
print("===================================")
dic01 = {95001: 56, 95004: 89, 95003: 98, 95002: 65}
keys_list = list(dic01.keys())
for i in keys_list:
print(i, ":", dic01[i])
3)使用keys和values来遍历,value:56
print("===================================")
dic01 = {95001: 56, 95004: 89, 95003: 98, 95002: 65}
keys_list = list(dic01.keys())
values_list = list(dic01.values())
for i in range(len(keys_list)):
print(keys_list[i], ":", values_list[i])
执行结果:
C:\python\python.exe C:/python/demo/file3.py
===================================
95001 56
95004 89
95003 98
95002 65
===================================
95001 : 56
95004 : 89
95003 : 98
95002 : 65
===================================
95001 : 56
95004 : 89
95003 : 98
95002 : 65
Process finished with exit code 0
标签:访问和遍历
原文地址:http://blog.51cto.com/13043937/2108858