zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    Taxes
    Tennis Championship
    Urbanization
    字符串的匹配
    Alyona and a tree
    Alyona and mex
    Alyona and flowers
    Alyona and copybooks
    Subordinates
    线程的暂停、恢复和终止
  • 原文地址:https://www.cnblogs.com/imeng/p/5056354.html
Copyright © 2011-2022 走看看