Dictionary
Dictionary
1. Set of key-value pairs (map)
2. The dictionary is a collection of data surrounded by braces "{}"
3. Dictionaries are unordered and access members by key in the dictionary. Variable, can be nested, can be used to modify the extension, etc., do not produce a new dictionary
4. The key of the dictionary can be a string (case sensitive), a numeric constant or a tuple (immutable type), and a key of the same dictionary can be mixed with a type. The key of the dictionary must be hash
The criteria for a tuple as a key is that the values within the tuple are immutable types
Copy Code code as follows:
A = (1,2) #可以作为键
b = (1,2,[3,4]) #不可以
5. The value of a dictionary can be any type, can be nested, can be modified freely
Statement
Several ways to create a dictionary:
1. Basic
Copy Code code as follows:
D = {} #空字典
D = {' name ': ' Tom ', ' Age ': 22}
#等价
D = {}
d[' name ' = ' Tom '
d[' age ' = 22
2.dict
Copy Code code as follows:
D = dict () #空
D = dict (name= ' Tom ', age=22)
D = dict ([(' Name ', ' Tom '), (' age ', 22)]
#等价
Keys = [' name ', ' age ']
values = [' Tom ', 22]
D = dict (Zip (keys,values))
3.fromkeys
Without specifying Default_value, default None
Copy Code code as follows:
>>> Dict.fromkeys ([' Name ', ' age '], ' default_value ')
{' Age ': ' Default_value ', ' name ': ' Default_value '}
Basic operations
0. Get help
Copy Code code as follows:
1. Whether the decision key exists in the dictionary
Copy Code code as follows:
If k in D: #k isn't in
DoSomething ()
2. Read
Copy Code code as follows:
D = {' A ': 1, ' B ': 2}
Print d[' A '] #得到1, but if the key does not exist, an exception keyerror is thrown. Caution, no use recommended
Print D.get (' C ', 3) #得到3, the Get method, if the key does not exist, returns the second parameter default_value. If no default_value is set to return none
Handling Missing-key errors in three ways, depending on the specific needs of
Copy Code code as follows:
If k in D:
Print D[k]
Try
Print D[k]
Except Keyerror:
DoSomething ()
Print D.get (k, default)
#等价 D[k] If k in D else default
3. Traverse
Mode 1:
Copy Code code as follows:
For key in D:
Print key, D[key]
#等价 for key in D.keys ()
Mode 2:
Copy Code code as follows:
For Key,value in D.items ():
Print key, value
4. Modify Mode 1: A key value pair
Copy Code code as follows:
Mode 2: Batch Add or update
Copy Code code as follows:
#另一个字典
D.update ({' key ': ' NewValue '}) #这里支持一整组值
#元组列表
D.update ([(' A ', 1), (' B ', 2]]) #每个元组两个元素, (Key,value)
#**key
D.update (c=3, e=4)
5. Delete
Copy Code code as follows:
Del d[' key ']
Value = D.pop (' key ') #删除并返回值
D.clear () #清空
6. Other:
Len (d) #长度
D.keys () #key列表
D.values () #value列表
D.items () # (key, value) list
c = d.copy () #浅拷贝
#返回迭代器, save memory
D.iterkeys ()
D.itervalues ()
D.iteritems ()
D.setdefault (' name ', ' Ken ') #若原来没有, set, otherwise the original value does not change
Other
1. Dictionary Sort by key
Copy Code code as follows:
Keys = D.keys ()
Keys.sort ()
For key in keys:
Print D.get (key)
Sort by value
Copy Code code as follows:
Sorted (D.items (), Lambda x,y:cmp (x[1],y[1))
Other than that:
Copy Code code as follows:
#假设d为字典
Sorted (d) #返回同 sorted (D.keys ()), which returns the key sort
2. Custom object as key
Have to:
Copy Code code as follows:
def __hash__ (self):
Pass
def __eq__ (self, Other):
Pass
3. Dictionary Copy Light copy:
Copy Code code as follows:
Deep copy must be in copy module
Copy Code code as follows:
Form copy Import Deepcopy
c = Deepcopy (d)
4. A use scenario assumes that there is a large list of L, assuming that the 10w record
There is a small list B, to determine if the element in B is in L
If:
Copy Code code as follows:
For I in B:
If I in L:
DoSomething ()
You'll find it very, very slow ... Because the second in statement will traverse the 10w bar ....
Improved:
Copy Code code as follows:
D = Dict.fromkeys (l)
For I in B:
If I in D:
DoSomething ()
#空间换时间, O (n)-> O (1)