python的字典非常方便,常用的遍历方法有以下几种:
1. 按照key遍历
myDict = {"C":98.2,"C++":98.4,"Java":97.5,"Python":99.5}
# 1.按照key遍历
for key in myDict:
print(key+": "+ str(myDict[key]) )
for key in myDict.keys():
print(key + ": " + str(myDict[key]))
# output:
# C: 98.2
# C++: 98.4
# Java: 97.5
# Python: 99.5
2. 按照value遍历
myDict = {"C":98.2,"C++":98.4,"Java":97.5,"Python":99.5}
# 2.按照value遍历
for value in myDict.values():
print(value)
# output:
# 98.2
# 98.4
# 97.5
# 99.5
3. 按照item遍历
myDict = {"C":98.2,"C++":98.4,"Java":97.5,"Python":99.5}
# 3.按照item遍历
for item in myDict.items():
print(item[0] + ": " + str(item[1]))
# output:
# C: 98.2
# C++: 98.4
# Java: 97.5
# Python: 99.5
4. 按照key-value对遍历
myDict = {"C":98.2,"C++":98.4,"Java":97.5,"Python":99.5}
# 4.按照key-value对遍历
for key,value in myDict.items():
print(key+": "+str(value))
# output:
# C: 98.2
# C++: 98.4
# Java: 97.5
# Python: 99.5
5.还可以先用sorted排序再遍历,这里按照value排序,默认的reverse=False按升序排序
myDict = {"C":98.2,"C++":98.4,"Java":97.5,"Python":99.5}
# 5.还可以先用sorted排序再遍历,这里按照value排序,默认的reverse=False按升序排序
sort_list = sorted(myDict.items(),key=lambda x:x[1],reverse=True)
for item in sort_list:
print(item[0]+": "+str(item[1]))
# output:
# Python: 99.5
# C++: 98.4
# C: 98.2
# Java: 97.5