码迷,mamicode.com
首页 > 编程语言 > 详细

python基础6(字典)

时间:2014-12-02 18:58:49      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   color   sp   for   strong   on   

映射:键值对的关系,键(key)映射值(value)

字典是Python唯一的映射类型

>>> phonebook = {wakey:1111,Ethon:2222,joho:3333}
>>> phonebook
{joho: 3333, wakey: 1111, Ethon: 2222}

扩展:映射类型与序列类型的区别

1、访问方式不同,序列类型用数字类型的键,而映射类型可以用其他对象类型做键(一般式字符串)

>>> lis = [a,b,c]
>>> lis[2]
c
>>> dic = {name:a,father:b,mother:c}
>>> dic[mother]
c

2、存储类型不同,映射类型的键,直接或间接地与值相关。

3、序列类型,有序之列;映射类型则无序之列

 

字典:

1、dict 函数

>>> items = [(name,gumby),(age,42)]  # 通过其它映射或键值对建立字典
>>> d = dict(items)
>>> d
{age: 42, name: gumby}
>>> 
>>> d = dict(name=Ethon,age=42)    # 通过关键字参数建立字典
>>> d
{age: 42, name: Ethon}

2、字典特点:

1)键可以是任何不可变类型(字典最强大的地方)

2)字典中的键可能自动添加

>>> x = {}     # 空字典
>>> x[2]=Ethon
>>> x
{2: Ethon}

3、字典方法

dict.clear():删除字典中所有元素

>>> x = {name:wakey,age:22}
>>> x.clear()
>>> x
{}

dict.copy():返回一个具有相同键值对的新字典

>>> x = {name:wakey,age:22}
>>> y = x.copy()
>>> y[name]=Ethon
>>> y
{age: 22, name: Ethon}
>>> x
{age: 22, name: wakey}

dict.formkeys():用给定的键创建新的字典

>>> {}.fromkeys([name,age])
{age: None, name: None}    # None 作为默认值

dict.get(key,default=None):返回对应键值

>>> d = {}
>>> print d.get(name)     
None        # get访问一个不存在的键时,可以得到None值

dict.has_key():检查键是否存在

>>> d = {}
>>> d.has_key(name)
False
>>> d[name]=Ethon
>>> d.has_key(name)
True

dict.items():将所有的字典项以列表的方式返回,项在返回时没有特定的顺序。

>>> d = {title:python web site,url:http://www.python.com}
>>> d.items()
[(url, http://www.python.com), (title, python web site)]

dict.keys():键的列表dict.values():值的列表

dict.pop():获得对应于给定键的值,然后将这个键-值对从字典中移除

>>> d = {x:1,y:2}
>>> d.pop(x)
1
>>> d
{y: 2}

dict.popitem():弹出列表最后的一个元素(随机弹出),若想一个一个的移除并处理项,这个方法很有用了。

>>> d = {title:python,url:www.python,com}
>>> d.popitem()
(url, www.python,com)
>>> d
{title: python}

dict.update():利用一个字典项更新另外一个字典

>>> d = {title:python,url:www.python,com}
>>> x = {title:python language website}
>>> d.update(x)
>>> d
{url: www.python,com, title: python language website}

 

python基础6(字典)

标签:style   blog   http   ar   color   sp   for   strong   on   

原文地址:http://www.cnblogs.com/wakey/p/4138183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!