Python基础:1.数据类型(字典)

提示:python版本:2.7,windows系统

1.字典(Dictionary)

  由Key-Value组成,一个Key只能对应一个Value

1 >>> colors = {'red': '#FF0000', 'orange': '#FF9900', 'yello': '#FFFF00'}
2 >>> print colors
3 {'orange': '#FF9900', 'yello': '#FFFF00', 'red': '#FF0000'}

  取值,如果key不存在则报错

1 >>> colors['orange']
2 '#FF9900'
3 >>> colors['green']
4 
5 Traceback (most recent call last):
6   File "<pyshell#3>", line 1, in <module>
7     colors['green']
8 KeyError: 'green'

  判断Key是否存在Dict中用【in】

1 >>> 'yello' in colors
2 True
3 >>> 'blue' in colors
4 False

  get方法,取值不存在也不会报错,还可以使用默认值

1 >>> colors.get('re')
2 >>> colors.get('red')
3 '#FF0000'
4 >>> colors.get('blue', '#0000FF')
5 '#0000FF'

 dict的key是不可变的,而python中List是可变的,所以不能用作Key。

posted @ 2015-12-18 10:49  阿克西斯教成员污米饭  阅读(283)  评论(0编辑  收藏  举报