1、三種常見的字典遍歷實現
def get_key_value(dics): '''遍歷所有鍵值對''' for key, value in dics.items(): print(f"{key}: {value}") def get_keys(dics): ''' 遍歷所有的鍵''' for key in dics.keys(): print(key) def get_values(dics): '''遍歷所有的值''' for value in dics.values(): print(value) if __name__ == "__main__": dics = { 'name': 'xiaopangyu', 'age': 18, 'sex': 'man', 'high': 180 } # 三種字典遍歷方法 print("========== 遍歷所有的key value ==========") get_key_value(dics) print("========== 遍歷所有的key ==========") get_keys(dics) print("========== 遍歷所有的value ==========") get_values(dics)
2、列印結果
name: xiaopangyu
age: 18
sex: man
high: 180
========== 遍歷所有的key ==========
name
age
sex
high
========== 遍歷所有的value ==========
xiaopangyu
18
man
180