操作示例
>>> d = {'one': 1, 'two': 2, 'three': 3} >>> len(d) 3 >>> 'two' in d True >>> 'two' not in d False >>> >>> d['three'] 3 >>> d['four'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'four' >>> d.get('three') 3 >>> d.get('four', 'default') 'default' >>> d {'one': 1, 'two': 2, 'three': 3} >>> d.setdefault('three', 'default') 3 >>> d {'one': 1, 'two': 2, 'three': 3} >>> d.setdefault('four', 'default') 'default' >>> d {'one': 1, 'two': 2, 'four': 'default', 'three': 3} >>> dict.fromkeys(['one', 'two', 'three']) {'one': None, 'two': None, 'three': None} >>> dict.fromkeys(['one', 'two', 'three'], 'default') {'one': 'default', 'two': 'default', 'three': 'default'} >>> >>> d.copy() {'one': 1, 'two': 2, 'four': 'default', 'three': 3} >>> d['four'] = 4 >>> d {'one': 1, 'two': 2, 'four': 4, 'three': 3} >>> d['five'] = 5 >>> d {'one': 1, 'two': 2, 'five': 5, 'four': 4, 'three': 3} >>> d.update({'two': 'II', 'six': 6}) >>> d {'one': 1, 'two': 'II', 'four': 4, 'five': 5, 'six': 6, 'three': 3} >>> d.update(two=2, seven=7) >>> d {'one': 1, 'two': 2, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'three': 3} >>> d.update([('three', 'III'), ('eight', 8)]) >>> d {'one': 1, 'two': 2, 'four': 4, 'five': 5, 'eight': 8, 'six': 6, 'seven': 7, 'three': 'III'} >>> >>> d.keys() dict_keys(['one', 'two', 'four', 'five', 'eight', 'six', 'seven', 'three']) >>> d.values() dict_values([1, 2, 4, 5, 8, 6, 7, 'III']) >>> d.items() dict_items([('one', 1), ('two', 2), ('four', 4), ('five', 5), ('eight', 8), ('six', 6), ('seven', 7), ('three', 'III')]) >>> iter(d) <dict_keyiterator object at 0x000001EA21A179A8> >>> iter(d.keys()) <dict_keyiterator object at 0x000001EA21A175E8> >>> >>> del d['eight'] >>> d {'one': 1, 'two': 2, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'three': 'III'} >>> d.popitem() ('one', 1) >>> d {'two': 2, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'three': 'III'} >>> d.pop('three') 'III' >>> d {'two': 2, 'four': 4, 'five': 5, 'six': 6, 'seven': 7} >>> d.pop('three') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'three' >>> d.pop('three',None) >>> d.pop('three','default') 'default' >>> d.clear() >>> d.popitem() Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'popitem(): dictionary is empty' 字典视图对象(Dictionary view objects)对于dict.keys()、dict.values()和dict.items()这些函数,在Python 2.x中返回的是list对象,而在Python 3.x中返回的是一个叫做字典视图的对象。