标签:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. #4.1字典的使用 >>> names=['Alice','Beth','Cecil','Dee-Dee','Earl'] >>> numbers=['2341','9102','3158','042','5551'] >>> names=['Alice','Beth','Cecil','Dee-Dee','Earl'] >>> numbers=['2341','9102','3158','042','5551'] >>> numbers[names.index('Cecil')] '3158' >>> 0142 98 >>> 0912 SyntaxError: invalid token >>> 0812 SyntaxError: invalid token #4.2创建和使用字典 >>> phonebook={'Alice':'2341','Beth':'9102','Cecil':'3258'} >>> phonebook['Cecil'] '3258' #4.2.1 dict函数 >>> items=[('name','Gumby'),('age',42)] >>> d = dict(items) >>> d {'age': 42, 'name': 'Gumby'} >>> d['name'] 'Gumby' >>> d = dict(name='Gumby', age=42) >>> d {'age': 42, 'name': 'Gumby'} #4.2.2 基本字典操作 #len(d)返回d中项(键值对)的数量 #d[k]返回关联到键k上的值 #d[k]=v将值v关联到键k上 #del d[k]删除键为k的项 #k in d检查d中是否包括键为k的项 #键的类型:字典的键能够是整型,浮点型(实型),字符串或元组. 字典的键能够是不论什么不可变类型. #在字典中检查键的成员资格比在列表中检查值的成员资格更有效,数据结构的规模越大,两者的效率差距越明显 >>> x=[] >>> x[42]='Foobar' Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> x[42]='Foobar' IndexError: list assignment index out of range >>> x={} >>> x[42]='Foobar' >>> x {42: 'Foobar'} #代码清单4-1 字典演示样例 #4.2.3 字典的格式化字符串 >>> phonebook {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'} >>> "Cecil's phone number is %(Cecil)s. " % phonebook "Cecil's phone number is 3258. " >>> template = '''<html> <head><title>%(title)s</title></head> <body> <h1>%(title)s</h1> <p>%(text)s</p> </body>''' >>> data = {'title':'My Home Page', 'text':'Welcome to my home page!'} >>> print template % data <html> <head><title>My Home Page</title></head> <body> <h1>My Home Page</h1> <p>Welcome to my home page!</p> </body> #4.2.4 字典方法 #1.clear方法 >>> d={} >>> d['name']='Gumby' >>> d['age']=42 >>> d {'age': 42, 'name': 'Gumby'} >>> returned_value = d.clear() >>> d {} >>> print returned_value None >>> x={} >>> y=x >>> x['key']='value' >>> y {'key': 'value'} >>> x={} >>> y {'key': 'value'} >>> >>> x={} >>> y=x >>> x['key']='value' >>> y {'key': 'value'} >>> x.clear() >>> y {} #2.copy方法,这种方法实现的是浅复制(shallow copy) >>> x={'username':'admin', 'machines':['foo','bar','baz']} >>> y=x.copy() >>> y['username']='mlh' >>> y['machines'].remove('bar') >>> y {'username': 'mlh', 'machines': ['foo', 'baz']} >>> x {'username': 'admin', 'machines': ['foo', 'baz']} #使用深复制(deep copy), 复制一个副本 >>> from copy import deepcopy >>> d={} >>> d['names']=''Alfred','Bertrand'] SyntaxError: invalid syntax >>> d['anmes']=['Afred','Bertrand'] >>> c=d.copy() >>> c {'anmes': ['Afred', 'Bertrand']} >>> d['names']=['Alfred','Bertrand'] >>> d {'names': ['Alfred', 'Bertrand'], 'anmes': ['Afred', 'Bertrand']} >>> d.clear() >>> d['names']=['Alfred','Bertrand'] >>> c=d.copy() >>> c {'names': ['Alfred', 'Bertrand']} >>> dc=deepcopy(d) >>> d['names'].append('Clive') >>> c {'names': ['Alfred', 'Bertrand', 'Clive']} >>> dc {'names': ['Alfred', 'Bertrand']} #3.fromkeys方法 >>> {}.fromkeys(['name','age']) {'age': None, 'name': None} >>> dict.fromkeys(['name','age']) {'age': None, 'name': None} >>> dict.fromkeys(['name','age'], '(unknown)') {'age': '(unknown)', 'name': '(unknown)'} >>> #4.get方法 >>> d={} >>> print d['name'] Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print d['name'] KeyError: 'name' >>> print d.get['name'] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print d.get['name'] TypeError: 'builtin_function_or_method' object has no attribute '__getitem__' >>> print d.get('name') None >>> d.get('name','N/A') 'N/A' >>> d['name']='Eric' >>> d.get('name') 'Eric' #代码清单4-2 字典方法演示样例 #5.has_key方法 >>> d={} >>> d.has_key('name') False >>> d['name']='Eric' >>> d.has_key('name') True #6.items和iteritems >>> d={'title':'Python Web Site', 'url':'http://www.python.org', 'spam':0} >>> d.items() [('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')] >>> it = d.iteritems() >>> it <dictionary-itemiterator object at 0x0134AF30> >>> list(it) #Convert the iterator to a list [('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')] #7.keys方法和iterkeys方法 #keys方法将字典中的键以列表形式返回,而iterkeys则返回键的迭代器 #8.pop方法 >>> d = {'x':1, 'y':2} >>> d.pop('x') 1 >>> d {'y': 2} >>> #9.popitem方法 >>> d={'url':'http://www.python.org', 'spam':0, 'title':'Python Web Site'} >>> d {'url': 'http://www.python.org', 'title': 'Python Web Site', 'spam': 0} >>> d.popitem() ('url', 'http://www.python.org') >>> d {'title': 'Python Web Site', 'spam': 0} >>> d={} >>> d.setdefault('name', 'N/A') 'N/A' >>> d {'name': 'N/A'} >>> d['name']='Gumby' >>> d.setdefault('name','N/A') 'Gumby' >>> d {'name': 'Gumby'} >>> d={} >>> print d.setdefault('name') None >>> d {'name': None} #11.update方法 >>> d={ 'title':'Python Web Site', 'url':'http://www.python.org', 'changed':'Mar 14 22:09:15 MET 2008' } >>> x={'title':'Python Language Website'} >>> d.update(x) >>> d {'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:15 MET 2008', 'title': 'Python Language Website'} #12. values方法和itervalues方法 >>> d={} >>> >>> d[1]=1 >>> d[2]=2 >>> d[3]=3 >>> d[4]=1 >>> d.values() [1, 2, 3, 1] >>> #4.3 小结 #映射:映射能够使用不论什么不可变对象标识元素. 最经常使用的类型是字符串和元组. Python唯一内建的映射类型是字典. #利用字典格式化字符串 #字典的方法 #4.3.1本章的新函数 #dict(seq) 用(键,值)对(或者映射和keyword參数)建立字典
字典演示样例
#coding=utf-8 #e4-1.py 字典演示样例 #简单数据库 #使用人名作为键的字典,每一个人用还有一个字典来表示,其键'phone'和'addr'分别表示他们的电话号码和地址. people = { 'Alice': { 'phone':'2341', 'addr':'Foo drive 23' }, 'Beth': { 'phone':'9102', 'addr':'Bar street 42' }, 'Cecil':{ 'phone':'3158', 'addr':'Baz avenue 90' } } #针对电话号码和地址使用的描写叙述性标签, 会在打印输出的时候用到 labels = { 'phone':'phone number', 'addr':'address' } name=raw_input('Name: ') #查找电话号码还是地址?使用正确的键: request = raw_input('Phone number (p) or address (a)?
') #使用正确的键: if request == 'p': key = 'phone' if request == 'a': key = 'addr' #假设名字是字典中的有效键才信息打印: if name in people: print "%s's %s is %s. " % (name, labels[key], people[name][key]) #python e4-1.py #Name: Beth #Phone number (p) or address (a)? p #Beth's phone number is 9102.
#coding=utf-8 #e4-2 #使用get()的简单数据库 #这里加入代码清单4-1中插入数据库的代码 people = { 'Alice': { 'phone':'2341', 'addr':'Foo drive 23' }, 'Beth': { 'phone':'9102', 'addr':'Bar street 42' }, 'Cecil':{ 'phone':'3158', 'addr':'Baz avenue 90' } } labels = { 'phone':'phone number', 'addr':'address' } name = raw_input('Name: ') #查找电话号码还是地址? request = raw_input('Phone number (p) or address(a)? ') #使用正确的键 key = request #假设请求既不是'p'也不是'a' if request == 'p' : key = 'phone' if request == 'a' : key = 'addr' #使用get()提供默认值: person = people.get(name, {}) label = labels.get(key ,key) result = person.get(key, 'not available') print "%s's %s is %s. " % (name, label, result) #python e4-2.py #Name: Beth #Phone number (p) or address(a)? a #Beth's address is Bar street 42. #python e4-2.py #Name: Cecil #Phone number (p) or address(a)? p #Cecil's phone number is 3158. #python e4-2.py #Name: Cecil #Phone number (p) or address(a)?x #Cecil's x is not available.
版权声明:本文博客原创文章,博客,未经同意,不得转载。
标签:
原文地址:http://www.cnblogs.com/gcczhongduan/p/4656193.html