Python--day19--collections module
Explanation of each module of common module 1:
The file name should not be the same as the module name: (the module itself is a py file)
collection module:
namedtuple method:
Example 1:
Example 2:
dequeue method: double-ended queue
Ordered Dictionary OrderedDict:
defaultdict default dictionary:
1 values = [11, 22, 33,44,55,66,77,88,99,90] 2 3 my_dict = {} 4 5 for value in values: 6 if value>66: 7 if my_dict.has_key('k1'): 8 my_dict['k1'].append(value) 9 else: 10 my_dict['k1'] = [value] 11 else: 12 if my_dict.has_key('k2'): 13 my_dict['k2'].append(value) 14 else: 15 my_dict['k2'] = [value]
1 from collections import defaultdict 2 3 values = [11, 22, 33,44,55,66,77,88,99,90] 4 5 my_dict = defaultdict(list) 6 7 for value in values: 8 if value>66: 9 my_dict['k1'].append(value) 10 else: 11 my_dict['k2'].append(value)
When used , if the referenced Key does not exist, it will be thrown . If you want to return a default value when the key does not exist, you can use :dict
KeyError
defaultdict
1 >>> from collections import defaultdict 2 >>> dd = defaultdict( lambda : ' N/A ' ) 3 >>> dd[ ' key1 ' ] = ' abc ' 4 >>> dd[ ' key1 ' ] # key1 exists 5 ' abc ' 6 >>> dd[ ' key2 ' ] # key2 does not exist, return default value 7 ' N/A '