Python dictionary operations and python dictionary operations
Today, I plan to write something every week to record my learning and mark it myself.
The dictionary is the most flexible built-in data structure in python. The dictionary isUnordered(The dictionary sequence is random to quickly execute the key search), python uses the optimal hash algorithm to find the key; the dictionary is similar to the map in java, however, there are not as many map types (such as HashMap and TreeMap) in java ).
Common dictionary operations
Assignment
D ={}# empty dictionary D = {"name": "zhangsan", "age": 23} # dictionary D containing two projects = {"fruit ": {"apple": 2, "orange": 1 }}# nested D = dict. fromkeys (["a", "B"], 2) # {'A': 2, 'B': 2} D = dict (zip (["name ", "age"], ["zhangsan", '23']) # {'age': '23', 'name': 'hangsan '}
Value
Name = D ["name"] age = D. get ("age", 0) # If the age attribute does not exist, set the value to 0 keys = D. keys () # obtain the key values = D. values () # obtain valueif 'name' in D: print "name is in D"
Delete
D. pop ('sex') # Delete del D ['name'] by key # Delete by key
Other operations
D_1 = {"sex": "male"} D. update (D_1) # merge dict
Write it here first, and then add it later.