【python】dict使用方法和快捷查找
字典的用法,dict的查找特别快捷。如果我们的项目经常用到搜索某些数据,最好用dict类型。认识dict¶peter@智普教育:~$ pythonPython 2.7.3 (default, Aug1 2012, 05:16:07) [GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for m
·
字典的用法,dict的查找特别快捷。如果我们的项目经常用到搜索某些数据,最好用dict类型。
认识dict¶
peter@智普教育:~$ pythonPython 2.7.3 (default, Aug 1 2012, 05:16:07)[GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> a={"name":"jike","age":30,"job":"python优秀工程师","level":"智普小天才"}>>> print a["level"]智普小天才>>> print a["age"]30
这就是字典,今年30岁的python工程师是一个天才。 和数据库结合非常完美。制作一个电话联系人也很实用。
上面的"name","age"等叫做key;
"jike",30,"智普小天才",叫做value。
获取所有的keys。
>>> a={"name":"jike","age":30,"job":"python优秀工程师","level":"智普小天才"}>>> b = a.keys()>>> print b['job', 'age', 'name', 'level']>>> type(b)<type 'list'>>>> c = a.values()>>> print c['python\xe4\xbc\x98\xe7\xa7\x80\xe5\xb7\xa5\xe7\xa8\x8b\xe5\xb8\x88', 30, 'jike', '\xe6\x99\xba\xe6\x99\xae\xe5\xb0\x8f\xe5\xa4\xa9\xe6\x89\x8d']>>> type(c)<type 'list'>>>>
上面的代码,你看懂了吗? 请解释一下。
注意:上面print c的时候有些乱码是python控制台的原因。
给dict添加内容¶
a={}a['email']='cool@jeapedu.com'
这样做可以吗?请试试。 list可以做如下动作吗?为什么?
list=[]list[5]=10
删除操作¶
peter@智普教育:~$ pythonPython 2.7.3 (default, Aug 1 2012, 05:16:07)[GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> a={"name":"jike","age":30,"job":"python优秀工程师","level":"智普小天才"}>>> for b in a: print b...jobagenamelevel>>> a.pop("name")'jike'>>> print a{'job': 'python\xe4\xbc\x98\xe7\xa7\x80\xe5\xb7\xa5\xe7\xa8\x8b\xe5\xb8\x88', 'age': 30, 'level': '\xe6\x99\xba\xe6\x99\xae\xe5\xb0\x8f\xe5\xa4\xa9\xe6\x89\x8d'}>>>>>> del a["job"]>>> print a{'age': 30, 'level': '\xe6\x99\xba\xe6\x99\xae\xe5\xb0\x8f\xe5\xa4\xa9\xe6\x89\x8d'}
如何判断key是否存在?¶
>>> a["age"]30>>> a["name"]Traceback (most recent call last):File "<stdin>", line 1, in <module>KeyError: 'name'
直接用会出错。
用for key in a: ?
还有更好的方法吗?
答案
code-comment: n1761:a.has_key("name")
获取键值的方法
a.get("age")a["age"]
区别是什么?
a.get比a["name"]更安全,如果key不存在。get函数返回空None,但不会出错。
update函数的用法
>>> print a{'age': 30, 'level': '\xe6\x99\xba\xe6\x99\xae\xe5\xb0\x8f\xe5\xa4\xa9\xe6\x89\x8d'}>>> a1={"hello":1}>>> a.update(a1)>>> print a{'age': 30, 'hello': 1, 'level': '\xe6\x99\xba\xe6\x99\xae\xe5\xb0\x8f\xe5\xa4\xa9\xe6\x89\x8d'}
获取key,value的另一个方法
In [4]: d.items()Out[4]: [(1, 'a'), (2, 'b'), (3, 'c')]
更多推荐



所有评论(0)