python中經常使用的字典內建函數
1、len(mapping) 返回映射的長度(鍵-值對的個數)
2、hash(obj) 返回obj的哈希值
>>> myDict = {‘name‘:‘earth‘, ‘port‘:‘80‘} >>> len(myDict) 2 >>> hash(‘name‘) 15034981
3、dict.copy() 返回字典(淺復制)的一個副本
>>> 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)
創建並返回一個新字典,以 seq 中的元素做該字典的鍵。val 做該字典中全部鍵相應的初始值(假設不提供此值,則默覺得 None)。
>>> seq = [‘name‘, ‘port‘] >>> myDict.fromkeys(seq) {‘name‘: None, ‘port‘: None}
6、dict.get(key)
對字典 dict 中的鍵 key,返回它相應的值 value,假設字典中不存在此鍵,則返回 default 的值(註意。參數 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()與它們相應的非叠代方法一樣,不同的是它們返回一個叠代子,而不是一個列表。
11、dict.pop(key[, default])
和方法 get()相似,假設字典中 key 鍵存在。刪除並返回 dict[key],假設 key 鍵不存在,且沒有給出 default 的值,引發 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‘}
python中經常使用的字典內建函數