对字典的操作稍有些陌生,在此记录一下。
字典的使用已{key:value}的形式存在,多个值以逗号分开。
字典的遍历共有三种方法,他们将返回类似列表的值,分别对应字典的键、值、键-值对。即keys()、values()、items()三种方法。
1.遍历所有的键值对
spam = {'color':'red','age':'42'} for i in spam.values(): print(i)
结果为:
red
42
2.遍历每个键
spam = {'color':'red','age':'42'} for i in spam.keys(): print(i)
结果为:
color
age
3.遍历键值对
spam = {'color':'red','age':'42'} for i in spam.items(): print(i)
结果为:
('color', 'red') ('age', '42')