標籤:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32Type "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'>>> 014298>>> 0912SyntaxError: invalid token>>> 0812SyntaxError: 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_valueNone>>> 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.
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
Python第一個基本教程4章 詞典: 當指數不工作時也