1. Construct the dictionary
- Create directly
dict1={}
dict1['key']=value- With the collections module
Import defaultdict from the collections module, defaultdict can implement a key corresponding to multiple values, to ensure that the order of inserted elements remains unchanged, you can use defaultdict (list), and then use the append function to add elements; add function to add an element
dict2=dd(list)dict2['a'].append(1)
dict2['a'].append(2)
dict2['b'].append(2)
dict2['c'].append(44)
dict2>>>defaultdict(<type 'list'>, {'a': [1, 2], 'c': [44], 'b': [2]})
- ordered dictionary
dict3['aa']=1
dict3['bb']=11
dict3['cc']=5
dict3>>>OrderedDict([('aa', 1), ('bb', 11) , ('cc', 5)])
2. Built-in functions
dir(dict) to see supported methods:'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', ' values'
- clear clears the elements in the dictionary
- copy Shallow copy
- fromkeys uses the sequence in fromkeys(seq, value) as the key of the new dictionary; value is the initial value, optional
- get 同dict[key]
- items returns an iterable key value
- values return value
- keys return key
- popitem returns and deletes a key-value pair
- update adds a new key-value pair
- setdefault is added if the key does not exist, similar to fromkeys