遍历字典
Python支持對字典的遍歷,有多種遍歷字典的方式:所有的鍵值對,鍵或者值。
遍歷所有的鍵值對:
people = {'name':'winter','age':'25',
'sex':'man',
}
for key,value in people.items():
print("\nkey:"+key)
print("value:"+value)
key:name
value:winter
key:age
value:25
key:sex
value:man
favourite_language={'winter':'python',
'thunder':'shell',
'amy':'C'}
for name,language in favourite_language.items():
print(name.title()+"`s favourite language is "+language.title()+ ' .')
Winter`s favourite language is Python .
Thunder`s favourite language is Shell .
Amy`s favourite language is C .
遍歷所有的鍵: favourite_language={'winter':'python',
'thunder':'shell',
'amy':'C'}
for name in favourite_language.keys(): #遍歷字典時默認遍歷所有的鍵,因此key()方法加不加都可以,加上之后更容易理解。
print(name)
winter
thunder
amy
按照順序遍歷所有鍵: favourite_language={'winter':'python',
'thunder':'shell',
'amy':'C'}
for name in sorted(favourite_language.keys()): #利用sorted()函數對字典的鍵進行一個排序。
print(name)
amy
thunder
winter
遍歷所有的值: favourite_language={'winter':'python',
'thunder':'shell',
'amy':'C',
'dongtian':'python'}
for language in favourite_language.values(): #使用方法values()可以遍歷字典所有的值。
print(language)
python
shell
C
python
這種做法提取字典中所有的值,但是沒有考慮是否有重復的。
favourite_language={'winter':'python',
'thunder':'shell',
'amy':'C',
'dongtian':'python'}
for language in set(favourite_language.values()): #使用方法values()可以遍歷字典所有的值,使用set()函數可以使值為唯一的
print(language)
shell
python
C
?
?
轉載于:https://www.cnblogs.com/winter1519/p/9259197.html
總結
- 上一篇: 解析DBF文件
- 下一篇: 平均出厂价790元/瓶 五粮液成不了第二