python之字典遍历方法

字典遍历分为三种:

  1. 遍历key
  2. 遍历value
  3. 遍历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)数组

posted @ 2019-04-15 20:07  twoint  阅读(4442)  评论(0编辑  收藏  举报