字典

1、    概述

字典是一个无序的数据集合,序列类型用有序的数字键做索引将数据以数组的形式存储。

在字典中能获得的有序集合只能是键的集合或者是值得集合,方法keys()或者value()返回一个列表,该列表是可以排序的,也可以使用items()方法得到包含键、值对的元组的列表来进行排序,字典本身是无序的。

哈希表拥有很好的性能,从而在使用键进行查询的时候,速度很快。

1.1    创建字典

创建字典有三种方法:

第一种直接使用大括号{}来进行创建并赋值,使用方法如下:

Diction= {“xy”:1,“ab”:2}

第二种使用工厂方法dict()来进行创建:

Diction= dict(([“x”,”y”],[1,2]))

第三种使用内建方法fromkeys()来创建默认的字典,字典元素中具有相同的值,当没有给出值得时候,默认为None:

Diction= {}.fromkeys((“x”,”y”),-1)

>>> diction = {"x":1,"y":2}

>>> diction

{'y': 2, 'x': 1}

>>> diction = dict(([1,2],["x","m"]))

>>> diction

{1: 2, 'x': 'm'}

>>> diction = {}.fromkeys(("x","y"),"abc")

>>> diction

{'y': 'abc', 'x': 'abc'}

>>>

1.2    访问字典中的值

访问字典中的值,可以直接使用key来进行访问,例如diction[“x”]

在进行遍历循环的时候,可以使用keys()来进行遍历,也可以直接对字典进行遍历:

>>> diction

{'y': 'abc', 'x': 'abc'}

>>> diction["y"]

'abc'

>>> for i in diction:

...     print i,diction[i]

...

y abc

x abc

>>> for i in diction.keys():

...     print i,diction[i]

...

y abc

x abc

>>> diction = {}.fromkeys(("x",1))

>>> diction

{'x': None, 1: None}

当在字典中不存在此键的时候,会返回一个错误,keyerror,在判断键是否在字典中,可以使用in或者是not in来进行判断:

>>> diction

{'x': None, 1: None}

>>> diction["kel"]

Traceback (most recent call last):

File "<stdin>", line 1, in ?

KeyError: 'kel'

>>> "kel" not in diction

True

>>> "x" in diction

True

1.3 更新字典

在修改字典的时候,可以直接添加一个新的数据项或者是新元素(一个键一个值),修改一个已经存在的数据项,或者删除一个已存在的数据项:

>>> diction

{'x': None, 1: None}

>>> diction["kel"] = "kel"

>>> diction

{'x': None, 'kel': 'kel', 1: None}

>>> diction["x"] = "change the string"

>>> diction

{'x': 'change the string', 'kel': 'kel', 1: None}

在进行print的时候,可以简化pring语句,如下:

>>> print "the x is %(x)s ,and the kel is %(kel)s" %diction

the x is change the string ,and the kel is kel

>>> diction

{'x': 'change the string', 'kel': 'kel', 1: None}

1.4 删除字典元素和字典

删除字典元素的例子如下:

>>> diction

{'x': 'change the string', 'kel': 'kel', 1: None}

>>> del diction["x"]

>>> diction

{'kel': 'kel', 1: None}

>>> diction.pop(1)

>>> diction

{'kel': 'kel'}

不要使用dict,list,file,bool,str,input,len这样的内建类型作为变量命名。

2、 字典操作符

字典可以喝所有标准类型操作符一起工作,但却不支持像拼接和重复这样的操作,这些操作队序列式有意义的,但是对字典类型不行。

字典可以进行比较,可以使用in或者not in来检查键是否存在于字典中。

在字典进行比较的时候,先比较字典的长度,然后比较字典的键,然后比较字典的值,当完全相同的时候,那么返回为0,也就是cmp函数的比较。

3、 字典相关函数

3.1 dict()

工厂函数用来创建字典,当不提供参数的时候,会生成空字典;当容器类对象作为一个参数传递给方法dict()的时候,必须是成对出现的。

>>> diction = dict(([1,2],[3,4]))

>>> diction

{1: 2, 3: 4}

>>> diction = dict(zip(("x","y"),(1,2)))

>>> diction

{'y': 2, 'x': 1}

>>> dict([("xy"[i-1],i) for i in range(1,3)])

{'y': 2, 'x': 1}

>>> diction = dict("1"=2,"3"=4)

SyntaxError: keyword can't be an expression

>>> diction = dict(x=2,y=4)

>>> diction

{'y': 4, 'x': 2}

3.2 sorted()

使用sorted内建函数得到一个有序的迭代:

>>> for eachKey in sorted(diction):

...     print "diction key",eachKey,"has value",diction[eachKey]

...

diction key x has value 2

diction key y has value 4

3.3 update()

使用update方法将一个字典的内容添加到另外一个字典中,重复的将被覆盖,部存在的键将被添加到字典中,clear()方法用来删除字典中的所有条目:

>>> diction

{'y': 4, 'x': 2}

>>> dictionA = {}.fromkeys((1,"x"),("nothin","something"))

>>> dictionA

{1: ('nothin', 'something'), 'x': ('nothin', 'something')}

>>> diction.update(dictionA)

>>> diction

{'y': 4, 'x': ('nothin', 'something'), 1: ('nothin', 'something')}

>>> diction.clear()

>>> diction

{}

3.4 copy()

Copy方法返回一个字典的副本,在这个时候使用的是浅复制,get()方法和键查找操作符[]相似,不同的是它允许你为不存在的键提供默认值,如果该键不存在,并且没有给出默认值,那么将返回None,在这个时候不用担心因键不存在从而导致的异常。

>>> diction

{'y': 2, 'x': 1}

>>> dictionA = diction.copy()

>>> dictionA

{'y': 2, 'x': 1}

>>> dictionA.get("x")

1

>>> dictionA.get("kel")

>>> dictionA.get("kel","no such key")

'no such key'

>>> dictionA["kel"] = "kel"

>>> dictionA

{'y': 2, 'x': 1, 'kel': 'kel'}

>>> diction

{'y': 2, 'x': 1}

>>> diction["new"] = "new"

>>> diction

{'y': 2, 'x': 1, 'new': 'new'}

>>> dictionA

{'y': 2, 'x': 1, 'kel': 'kel'}

3.5 setdefault()

Setdefault方法主要用来检查字典中是否含有某键,如果键存在,那么取值;如果键部存在,那么将这个键进行复制,并返回值:

>>> diction

{'y': 2, 'x': 1}

>>> diction.setdefault("y","kel")

2

>>> diction

{'y': 2, 'x': 1}

>>> diction.setdefault("kel","setdefault")

'setdefault'

>>> diction

{'y': 2, 'x': 1, 'kel': 'setdefault'}

3.6 fromkeys()

Fromkeys主要用来创建字典,如下所示:

>>> {}.fromkeys("xyz")

{'y': None, 'x': None, 'z': None}

>>> {}.fromkeys(("kel","other"),True)

{'kel': True, 'other': True}

3.7 其他方法

Keys(),items(),values()方法的返回值都是列表,在数据集很大的时候会导致很难处理,从而出现了方法iteritems(),iterkeys(),itervalues(),使用这些方法的时候比较节省内存。

python字典概述的更多相关文章

  1. Python字典和集合

    Python字典操作与遍历: 1.http://www.cnblogs.com/rubylouvre/archive/2011/06/19/2084739.html 2.http://5iqiong. ...

  2. python 字典排序 关于sort()、reversed()、sorted()

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  3. python字典中的元素类型

    python字典默认的是string item={"browser " : 'webdriver.irefox()', 'url' : 'http://xxx.com'} 如果这样 ...

  4. python字典copy()方法

    python 字典的copy()方法表面看就是深copy啊,明显独立 d = {'a':1, 'b':2} c = d.copy() print('d=%s c=%s' % (d, c)) Code1 ...

  5. python 字典实现类似c的switch case

    #python 字典实现类似c的switch def print_hi(): print('hi') def print_hello(): print('hello') def print_goodb ...

  6. python字典的常用操作方法

    Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串.数字.元组等其他容器模型.本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建.访问.删除.其它操作等,需 ...

  7. Python 字典(Dictionary)操作详解

    Python 字典(Dictionary)的详细操作方法. Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串.数字.元组等其他容器模型. 一.创建字典 字典由键和对应值成对组成.字 ...

  8. Python 字典(Dictionary) get()方法

    描述 Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值. 语法 get()方法语法: dict.get(key, default=None) 参数 ...

  9. Python 字典(Dictionary) setdefault()方法

    描述 Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值. 语法 setdefault()方法语法: ...

随机推荐

  1. Highcharts axja 获取json对象动态生成报表生成

    最近做个项目,项目经理想做一个统计报表,在网上查看些资料就选用Highchars 这里和大家分享下使用心得. 重点说明此代码是针对一个报表显示多个项对比显示. 直接贴代码:web端 <scrip ...

  2. 也谈JavaScript闭包

    闭包对于很多JavaScript初学者来说,都是比较难以理解的一个概念.其实,闭包并不是那么难以掌握的,理解闭包,只需要学会3个的基本事实. 首先我们来看第一个事实,JavaScript允许当前函数引 ...

  3. dojo 一 require 路径问题

    dojo.baseUrl baseUrl用来存储dojo.js存放 的跟目录,例如dojo.js的路径是“/web/scripts/dojo-1.3/dojo/dojo.js”则baseUrl为“/w ...

  4. YTU 2617: B C++时间类的运算符重载

    2617: B C++时间类的运算符重载 时间限制: 1 Sec  内存限制: 128 MB 提交: 284  解决: 108 题目描述 C++时间类的运算符重载 定义一个时间类Time,其数据成员为 ...

  5. Android HTTPS(4)直接用SSLSocket,黑名单,客户端证书

    Warnings About Using SSLSocket Directly So far, the examples have focused on HTTPS using HttpsURLCon ...

  6. hibernate自动生成映射文件

    映射文件是O/R Mapping的关键,相当于控制中心.当数据库表较多时,手动配置该映射文件非常耗时.为了快速开发程序,使开发人员的注意力集中到业务逻辑上来,Hibernate官方提供的MiddleG ...

  7. 不同浏览器JS获取浏览器高度和宽度

    摘自:http://blog.csdn.net/lai_gb/archive/2009/07/04/4320956.aspx IE中: document.body.clientWidth ==> ...

  8. UVa 424 Integer Inquiry

    之前杭电上也做过a + b的高精度的题,不过这道题的区别是有多组数据. 之前做的时候开了3个字符数组a,b,c,在计算的时候还要比较a,b长度,短的那个还要加'0',还设置了一个add来存放进位. 现 ...

  9. UVa 129 Krypton Factor【回溯】

    学习的紫书的回溯,理解起来还是好困难的说啊= = #include<iostream> #include<cstdio> #include<cstring> #in ...

  10. [Swift系列]002-基础语法

    基础语法就那老几样,很快可以说完 [常量.变量] 1.变量用 var,系统自动去判断类型,但变量再次赋值需保持数据类型一致 var  a=50 相信用过js/java/C#的,对这个var都不陌生 使 ...