python怎么遍历字典

首先需要创建一个字典:

dict = {
    '小明':1,
    '小红':2,
    '小李':3
}

1.遍历key
(1)

for key in dict:
    print(key)

(2)

for key in dict.keys():
    print(key)

2.遍历value
(1)

for value in dict.values():
    print(value)

3.同时遍历key和value
(1)

for key,value in dict.items():
    print('key:',key,'value:',value)

(2)

for kv in dict.items():
    print(kv)

你可能感兴趣的:(python,开发语言)