字典用{}表示
{0:0}//第一个0表示key ,第二个0表示values

点击(此处)折叠或打开

  1. >>> dic={0:0,1:1,2:2}
  2. >>> dic[0]
  3. 0
  4. >>> dic[2]
  5. 2
  6. >>> dic[1]
  7. 1
  8. /*获取key values*/
  9. >>> dic.keys()
    [0, 1, 2]
    >>> dic.values()
    [0, 1, 2]


key分别是'name'    'age'    'gender'

点击(此处)折叠或打开

  1. >>>
  2. dic1={'name':'milo','age':30,'gender':'male'}
  3. >>>dic1['name']
  4. 'milo'
  5. >>> dic1['age']
    30
    >>> dic1['gender']
    'male'


访问字典
取值key

点击(此处)折叠或打开

  1. >>> dic1
  2. {'gender': 'male', 'age': 30, 'name': 'milo'}
  3. >>> for k in dic1:
  4. ... print k
  5. ...
  6. gender
  7. age
  8. name
  9. >>> for k in dic1:
    ...     dic1[k]
    ...
    'male'
    30
    'milo'


更改字典取值
1.增加key
/*注意增加的顺序随机*/
>>> dic2['tel']='12345678'
>>> dic2
{1: '123', 'tel': '12345678', 'milo': 'milo', 'x': 456}

2.
/*删除并返回相应的值  .pop*/
>>> dic1=dic2.pop('tel')
>>> print dic1
12345678


/*删除name选项*/
>>> del dic1['name']
>>> dic1
{'gender': 'male', 'age': 30}
/*删除全部元素*/
>>> dic1.clear()
>>> dic1
{}
/*删除整个字典*/
>>>del dic1
>>>dic1 error
3.当字典中不存在的值,返回error
>>> dic
{0: 0, 1: 1, 2: 2}
>>> dic.get(3)
>>> dic.get(3,'error')
'error'






10-05 06:20