Python BASICS (dict class)
4. Dictionary (dict class) Tips: All of the following methods are class methods, and the first parameter is self, which is not uniform. The methods include: 1. clear () # clear all contents of the dictionary >>> d {1: 'A' }>> d. clear () >>> name {}2, fromkeys (k, v) # quickly create a dictionary with the same value. k is the key, the values are all v >>> d ={}>> d. fromkeys (range (5), () {0: (), 1: (), 2: (), 3: (), 4 :()} 3. get (k, d = none) # based on the key value, the d parameter indicates that if the key does not exist, the default value returned is null >>> d {0: [], 1: '20140901', 2: [], 3: [], 4: []} >>> d. get (1) '20140901'> d. get (5, 'no') 'no' 4, has_key (k) # key 5, items () # return all key-value pairs in the form of a list> d. items () [(0, []), (1, '20140901'), (2, []), (3, []), (4, [])] 6. keys () # return all keys in the form of a list> d. keys () [0, 1, 2, 3, 4] 7. values () # return all values in the form of a list >>> d. values () [[], '20140901', [], [], [] 8, pop (k, d = none) # Delete the specified key, the d parameter indicates that if the key does not exist, the default value returned is null by default> d. pop (2) [] >>> d {0: [], 1: '000000', 3: [], 4: []} 9, popitem () # randomly delete a key-Value Pair >>> d. popitem () (0, []) >>> d {1: '000000', 3: [], 4: []} 10, setdefault (k, d = none) # If the key does not exist, it is created. If the key exists, an existing value is returned without modification >>>> d {1: '123456', 3: [], 4: [] >>> d. Setdefault (0, 'abc') # The key with the name 0 does not exist, so it will be created 'abc' >>> d {0: 'abc', 1: '123 ', 3: [], 4: [] }>>> d. setdefault (1, 'abc') # The key with the name of 1 exists, so the value of this key is returned without modifying '20170' >>> d {0: 'abc', 1: '20140901', 3: [], 4: []} 11, update (x) # use a new dictionary x to update the current dictionary. If the key exists, the value is updated, if the key does not exist, create a key and assign a value. >>> D {0: 'abc', 1: '123', 3: [], 4: [] >>>> e = {0: 'bcd', 5: [] >>> d. update (e) >>> d {0: 'bcd', 1: '000000', 3: [], 4: [], 5: []}