遍历字典:
前置基础知识:
dict.keys() # 字典所有的键
dict.values() # 字典所有的值
dict.items() # 所有的键值对
不同种方式遍历字典:
默认方式为遍历字典的键(key)
temperature_list={"001": 38, "002": 37, "003": 38.5}
for staff in temperature_list:
temperature = temperature_list[staff]
if temperature >= 38:
print(staff)
for staff in dict.keys():遍历键
temperature_list={"001": 38, "002": 37, "003": 38.5}
for staff in temperature_list.keys():
temperature = temperature_list[staff]
if temperature >= 38:
print(staff)
for staff in dict.iems遍历键值对
temperature_list={"001": 38, "002": 37, "003": 38.5}
for staff in temperature_list.items():
id = staff[0]
temperature = staff[1]
if temperature>=38:
print(id)
遍历键值对也可以用更简洁的遍历方式:
temperature_list={"001": 38, "002": 37, "003": 38.5}
for staff_id, staff_temperature in temperature_list.items():
if staff_temperature >= 38:
print(staff_id)