首页 > 文章列表 > Python字典遍历的三种情况

Python字典遍历的三种情况

Python字典
265 2022-08-07

1、遍历字典中所有的键-值对

使用for循环和item()方法遍历字典中的所有键值对,如下例所示:

car = {'color':'red','type':'SUV','age':2}
for key,value in car.items():
print("\nKey: " + key)
print("Value: " + str(value))

2、遍历字典中所有的键

使用for循环和key()方法遍历字典中的所有键,如下例所示:

car = {'color':'red','type':'SUV','age':2}
for key in car.keys():
print("Key: " + key)

3、遍历字典中所有的值

使用for循环和values()方法遍历字典中的所有值,如下例所示:

car = {'color':'red','type':'SUV','age':2}
for value in car.values():
print("value: " + str(value))