python中字典的遍历

时间:2023-01-28 23:38:00
用ipython运行情况如下:
#新建字典
In [1]: name_cards = {'name':'sunwukong','QQ':'123124','addr':'秦皇岛'} #生成key对象
In [2]: name_cards.keys()
Out[2]: dict_keys(['name', 'QQ', 'addr']) #生成value对象
In [3]: name_cards.values()
Out[3]: dict_values(['sunwukong', '123124', '秦皇岛']) ##生成item对象
In [4]: name_cards.items()
Out[4]: dict_items([('name', 'sunwukong'), ('QQ', '123124'), ('addr', '秦皇岛')]) #python的解包
In [5]: a,b = (3,5) In [6]: a
Out[6]: 3 In [7]: b
Out[7]: 5 #遍历key
In [8]: for key in name_cards.keys():
...: print(key)
...:
name
QQ
addr #遍历value
In [9]: for value in name_cards.values():
...: print(value)
...:
sunwukong
123124
秦皇岛 #用解包的方法遍历key,value
In [10]: for key,value in name_cards.items():
...: print(key,value)
...:
name sunwukong
QQ 123124
addr 秦皇岛