python字典的常用操作方法


Python字典是另一種可變容器模型(無序),且可存儲任意類型對象,如字符串、數字、元組等其他容器模型。本文章主要介紹Python中字典(Dict)的詳解操作方法,包含創建、訪問、刪除、其它操作等,需要的朋友可以參考下。

字典由鍵和對應值成對組成。字典也被稱作關聯數組或哈希表。基本語法如下:

1.創建字典

1 >>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
2 技巧:
3 字典中包含列表:dict={'yangrong':['23','IT'],"xiaohei":['22','dota']}
4 字典中包含字典:dict={'yangrong':{"age":"23","job":"IT"},"xiaohei":{"'age':'22','job':'dota'"}}
5 注意:
6 每個鍵與值用冒號隔開(:),每對用逗號,每對用逗號分割,整體放在花括號中({})。
7 鍵必須獨一無二,但值則不必。

2.訪問字典里的值

 1 >>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
 2 >>> print(dict['ob1'])
 3 computer
 4 如果用字典里沒有的鍵訪問數據,會輸出錯誤如下:
 5 >>> print(dict['ob4'])
 6 Traceback (most recent call last):
 7   File "<pyshell#110>", line 1, in <module>
 8     print(dict['ob4'])
 9 
10 訪問所有值
11 >>> dict1 = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
12 >>> for key in dict1:
13     print(key,dict1[key])    
14 ob3 printer
15 ob2 mouse
16 ob1 computer

 

3.修改字典

1 >>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
2 >>> dict['ob1']='book'
3 >>> print(dict)
4 {'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'book'}

4.刪除字典

 1 能刪單一的元素  2 >>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
 3 >>> del dict['ob1']
 4 >>> print(dict)
 5 {'ob3': 'printer', 'ob2': 'mouse'}
 6 
 7 刪除字典中所有元素  
 8 >>> dict1={'ob1':'computer','ob2':'mouse','ob1':'printer'}
 9 >>> dict1.clear()
10 >>> print(dict1)
11 {}
12 
13 
14 刪除整個字典,刪除后訪問字典會拋出異常。 15 >>> dict1 = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
16 >>> del dict1
17 >>> print(dict1)
18 Traceback (most recent call last):
19   File "<pyshell#121>", line 1, in <module>
20     print(dict1)
21 NameError: name 'dict1' is not defined

5.更新字典

1 update()方法可以用來將一個字典的內容添加到另外一個字典中:
2 >>> dict1 = {'ob1':'computer', 'ob2':'mouse'}
3 >>> dict2={'ob3':'printer'}
4 >>> dict1.update(dict2)
5 >>> print(dict1)
6 {'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'computer'}

6.映射類型相關的函數  

 1 >>> dict(x=1, y=2)  
 2 {'y': 2, 'x': 1}  
 3 >>> dict8 = dict(x=1, y=2)  
 4 >>> dict8  
 5 {'y': 2, 'x': 1}  
 6 >>> dict9 = dict(**dict8)  
 7 >>> dict9  
 8 {'y': 2, 'x': 1}  
 9   
10 dict9 = dict8.copy()  

7.字典鍵的特性

 1 字典值可以沒有限制地取任何python對象,既可以是標准的對象,也可以是用戶定義的,但鍵不行。
 2 兩個重要的點需要記住:
 3 1)不允許同一個鍵出現兩次。創建時如果同一個鍵被賦值兩次,后一個值會被記住    
 4 >>> dict1={'ob1':'computer','ob2':'mouse','ob1':'printer'}
 5 >>> print(dict1)
 6 {'ob2': 'mouse', 'ob1': 'printer'}
 7     
 8 2)鍵必須不可變,所以可以用數,字符串或元組充當,用列表就不行
 9 >>> dict1 = {['ob1']:'computer', 'ob2':'mouse', 'ob3':'printer'}
10 Traceback (most recent call last):
11   File "<pyshell#125>", line 1, in <module>
12     dict1 = {['ob1']:'computer', 'ob2':'mouse', 'ob3':'printer'}
13 TypeError: unhashable type: 'list'

8.字典內置函數&方法

Python字典包含了以下內置函數: 1、cmp(dict1, dict2):比較兩個字典元素。(python3后不可用)
2、len(dict):計算字典元素個數,即鍵的總數。
3、str(dict):輸出字典可打印的字符串。
4、type(variable):返回輸入的變量類型,如果變量是字典就返回字典類型。

Python字典包含了以下內置方法: 1、radiansdict.clear():刪除字典內所有元素
2、radiansdict.copy():返回一個字典的淺復制
3、radiansdict.fromkeys():創建一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值
4、radiansdict.get(key, default=None):返回指定鍵的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果鍵在字典dict里返回true,否則返回false
6、radiansdict.items():以列表返回可遍歷的(鍵, 值) 元組數組
7、radiansdict.keys():以列表返回一個字典所有的鍵
8、radiansdict.setdefault(key, default=None):和get()類似, 但如果鍵不已經存在於字典中,將會添加鍵並將值設為default
9、radiansdict.update(dict2):把字典dict2的鍵/值對更新到dict里
10、radiansdict.values():以列表返回字典中的所有值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM