【Python】学习笔记十:字典

字典是Python中唯一的映射类型(哈希表)

字典的对象时可变的,但字典的键值必须是用不可变对象,并且一个字典中可以使用不同类型的键值

1.定义字典

        dict={key1:value1,key2:value2...}

例子:

>>> dict={'name':'OLIVER','age':24,'gender':'male'}
>>> dict['name']
'OLIVER'
>>> dict['age']
24
>>> dict['gender']
'male'

2.特殊定义字典

>>> a=100
>>> b=101
>>> dict4={a:'OLIVER','b':'QIN'}
>>> dict4[100]
'OLIVER'
>>> dict4
{100: 'OLIVER', 'b': 'QIN'}

 3.取出字典中的值

这里以上述定义的dict为例子

#获取key值
>>> for k in dict:
... print(k)
...
name
age
gender
#获取value值
>>> for k in dict:
...     print(dict[k])
...
OLIVER
24
male

4.字典key增加、删除、修改

4.1增加

>>> dict['tel']='12345678'
>>> dict
{'name': 'OLIVER', 'age': 24, 'tel': '12345678', 'gender': 'male'}

4.2删除

#删除其中一个元素
>>> del(dict['tel'])
>>> dict
{'name': 'OLIVER', 'age': 24, 'gender': 'male'}

#pop弹出某个元素,与del效果一样
>>> dict.pop('age')
24
>>> dict
{'name': 'OLIVER', 'gender': 'male'}
>>>

#清除所有元素
>>> dict.clear()
>>> dict
{}

#删除整个字典
>>> del(dict)

4.3修改

>>> dict['tel']='0000000'
>>> dict
{'name': 'OLIVER', 'age': 24, 'tel': '0000000', 'gender': 'male'}

 5.字典中的get方法

当所取key值在字典中不存在的时候,需要给出默认值,否则就会报错

语法:dict.get(key,dafault=none):返回key的value,如果改键不存在,返回default指定的值。

>>> dict5={'name':'jack','age':23}
>>> dict5.get(4,'error')
'error'

 

posted @ 2016-11-16 22:45  OLIVER_QIN  阅读(313)  评论(0编辑  收藏  举报