python之字典遍历方法
字典遍历分为三种:
- 遍历key
- 遍历value
- 遍历key-value
key遍历:
>>> person={'name':'lizhong','age':'26','city':'BeiJing'} >>> for key in person.keys(): print(key) name age city
value遍历:
>>> for value in person.values(): print(value) lizhong 26 BeiJing
key-value遍历:
>>> for key, value in person.items(): print(key, value) name lizhong age 26 city BeiJing
关于items()
>>> person {'name': 'lizhong', 'age': '26', 'city': 'BeiJing'} >>> person.items() dict_items([('name', 'lizhong'), ('age', '26'), ('city', 'BeiJing')])
由以上可得:items()以列表(list)的方式返回可遍历的(key, value)元组(tuple)数组