Starting today, I plan to write something every week to record my learning and mark it myself.
Dictionary is the most flexible built-in data structure in Python. A dictionary is an unordered collection (the order of the dictionary is random to quickly perform key lookups). Python uses an optimized hashing algorithm to find keys; a dictionary is similar to that in Java. map, but there are not as many types as map in java (HashMap, TreeMap, etc.).
Common dictionary operations
Assignment
D = {} # 空字典 D = {"name": "zhangsan", "age": 23} # 包含2个项目的字典 D = {"fruit": {"apple": 2, "orange": 1}} # 嵌套 D = dict.fromkeys(["a", "b"], 2) # {'a': 2, 'b': 2} D = dict(zip(["name", "age"], ["zhangsan", '23'])) # {'age': '23', 'name': 'zhangsan'}
Value
name = D["name"] age = D.get("age", 0) # 如果不存在age属性就取值为0 keys = D.keys() # 获取键 values = D.values() # 获取value if 'name' in D: print "name is in D"
Delete
D.pop('sex') # 根据key删除 del D['name'] # 根据key删除
Other operations
D_1 = {"sex": "male"} D.update(D_1) # 合并dict