iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0

以有序的方式走訪dict

利用sorted(dict.keys())

# loop over the keys in sorted order,
demo = { 'height': 170, 'weight': 58, 'age': 20 }
for key in sorted(demo.keys()):
    print (key, demo[key])

# age 20
# height 170
# weight 58

利用key或value作過濾

# filter
demo2 = dict(Mary=80, Jack=90, Smith=60, John=58, Tom=95, Jane=88, Tina=46)
greater_than_ninety = dict((key, value) for key, value in demo2.items() if value >= 90)
less_than_sixty = dict((key, value) for key, value in demo2.items() if value <= 60)
print( "greater_than_ninety: {}".format(greater_than_ninety) )
print( "less_than_sixty: {}".format(less_than_sixty) )

參考


上一篇
Day12-Dictionary-特性
下一篇
Day14-Tuple
系列文
if len(learning.python) == 30:31

尚未有邦友留言

立即登入留言