Python学习之:dictionary的注意事项
- 初始化dictionary
dict_1 = dict(red = 12, blue = 20, green = 14, grey = 10)
print(dict_1)
output:
{‘red’: 12, ‘blue’: 20, ‘green’: 14, ‘grey’: 10}
- dictionary的for循环
dict_1 = dict(red = 12, blue = 20, green = 14, grey = 10)
total = 0
for color in dict_1:
print(color)
print(type(color))
total += dict_1[color]
print("the total num is:", total)
上面的循环变量color是字典dict_1中元素的索引,由输出的结果可知索引变量的类型
-
dictionary的属性:keys(), values()
dictionary数据对象的属性keys()可以展示出它的索引,values()可以展示出所有的值。返回的类型分别是dict_keys和dict_values类型。
dict_1 = dict(red = 12, blue = 20, green = 14, grey = 10)
print(dict_1.keys())
print(type(dict_1.keys()))
print(dict_1.values())
print(type(dict_1.values()))
output:
注意:
生成的dict_keys和dict_values都是不可以像上面那种方式调用的