Python常見字典內(nèi)建函數(shù)用法示例
本文實例講述了Python常見字典內(nèi)建函數(shù)用法。分享給大家供大家參考,具體如下:
1、len(mapping)
返回映射的長度(鍵-值對的個數(shù))
2、hash(obj)
返回obj的哈希值
>>> myDict = {'name':'earth', 'port':'80'} >>> len(myDict) 2 >>> hash('name') 15034981
3、dict.copy()
返回字典(淺復(fù)制)的一個副本
>>> myDict = {'name':'earth', 'port':'80'} >>> yourDict = myDict.copy() >>> yourDict {'name': 'earth', 'port': '80'} >>> id(myDict)41816664L >>> id(yourDict) 41819544L
4、dict.clear()
刪除字典中所有元素
>>> myDict.clear() >>> myDict {}
5、dict.fromkeys(seq, val=None)
創(chuàng)建并返回一個新字典,以 seq 中的元素做該字典的鍵,val 做該字典中所有鍵對應(yīng)的初始值(如果不提供此值,則默認為 None)。
>>> seq = ['name', 'port'] >>> myDict.fromkeys(seq) {'name': None, 'port': None}
6、dict.get(key)
對字典 dict 中的鍵 key,返回它對應(yīng)的值 value,如果字典中不存在此鍵,則返回 default 的值(注意,參數(shù) default 的默認值為 None)。
>>> myDict = {'name':'earth', 'port':'80'} >>> myDict.get('name') 'earth' >>> print myDict.get('home') None
7、dict.items()
返回一個包含字典中(鍵, 值)對元組的列表
>>> myDict.items() [('name', 'earth'), ('port', '80')]
8、dict.keys()
返回一個包含字典中鍵的列表
9、dict.values()
返回一個包含字典中所有值的列表
>>> myDict.keys() ['name', 'port'] >>> myDict.values() ['earth', '80']
10、dict.iter()
方法 iteritems(),
iterkeys()
, itervalues()
與它們對應(yīng)的非迭代方法一樣,不同的是它們返回一個迭代子,而不是一個列表。
11、dict.pop(key[, default])
和方法 get()相似,如果字典中 key 鍵存在,刪除并返回 dict[key],如果 key 鍵不存在,且沒有給出 default 的值,引發(fā) KeyError 異常。
>>> myDict.pop('port') '80' >>> myDict {'name': 'earth'} >>> myDict.pop('port', 'No such key!') 'No such key!'
12、dict.setdefault(key, default=None)
和方法 set()
相似,如果字典中不存在 key 鍵,由 dict[key]=default
為它賦值。
>>> myDict.setdefault('port', '8080') '8080' >>> myDict {'name': 'earth', 'port': '8080'}
13、dict.update(dict2)
將字典 dict2 的鍵-值對添加到字典 dict。
>>> yourDict = {'language':'Python'} >>> yourDict {'language': 'Python'} >>> myDict.update(yourDict) >>> myDict {'name': 'earth', 'language': 'Python', 'port': '8080'}
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
- Python 把序列轉(zhuǎn)換為元組的函數(shù)tuple方法
- Python從函數(shù)參數(shù)類型引出元組實例分析
- python3 字符串/列表/元組(str/list/tuple)相互轉(zhuǎn)換方法及join()函數(shù)的使用
- python中的字典操作及字典函數(shù)
- 詳解python的sorted函數(shù)對字典按key排序和按value排序
- Python字典,函數(shù),全局變量代碼解析
- Python入門教程5. 字典基本操作【定義、運算、常用函數(shù)】
- Python 字典(Dictionary)操作詳解
- Python中字典創(chuàng)建、遍歷、添加等實用操作技巧合集
- Python字符串、元組、列表、字典互相轉(zhuǎn)換的方法
- python元組和字典的內(nèi)建函數(shù)實例詳解

一起解密Python中的*args和**kwargs無限可能的函數(shù)參數(shù)

PyCharm 2020.1版安裝破解注冊碼永久激活(激活到2089年)