A dictionary is the most flexible built-in data structure in python, and a dictionary is an unordered set (the dictionary is randomly ordered for fast key search execution). python uses the optimal hash algorithm to find keys; the dictionary is similar to map in java, but it does not have as many types (such as HashMap and TreeMap) as map in java ).
Today, I plan to write something every week to record my learning and mark it myself.
A dictionary is the most flexible built-in data structure in python, and a dictionary is an unordered set (the dictionary is randomly ordered for fast key search execution). python uses the optimal hash algorithm to find keys; the dictionary is similar to map in java, but it does not have as many types (such as HashMap and TreeMap) as map 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