Dictionary (dict)
Definition: Dictionary type in other languages, also known as map, is a type of mapping, and {key:value} unordered, its keywords must be immutable type (such as: tuple/String), in the same dictionary must be different keywords (if the same keyword, the first one will prevail)
Second, the operation
1. Create:
dic={} #创建一个空字典
dic={' Jack ': 1234, ' Tom ': 1226}
2. References and modifications:
(1) Heuristic value: Dic.get (' age ') #试探字典中是否存在age这个键, returns none if not present
(2) Display reference and modify: dic[' age ']=1238
3. Delete and clear:
(1) Delete a pair of key values: Del dic[' age '] or dic.pop (' age ')
(2) Delete entire dictionary: del dic
(3) Empty dictionary (not delete dictionary): Dic.clear ()
4. Merging dictionaries:
(1) modify directly in the original dictionary: Dic1.update (DIC2) #dic1被修改了
(2) Key value pairs of two dictionaries as new dictionaries: dict (Zip (dic1,dic2))
5. Take Keys/values/items operation:
Dic={' A ': 1, ' B ': 2}
List (Dic.keys ()) #返回key的列表
List (Dic.values ()) #返回value的列表
List (Dic.items ()) #返回键值对的列表
6. Length measurement: Len (dict) #返回的是字典的键值对个数
7. Member test: ' A ' in dic #测试键 ' A ' is in the dictionary, if it returns true
8. Traverse the dictionary:
(1) Press key to traverse:
For key in Dic.keys ():
Print (key)
(2) Traverse by value:
For value in Dic.values ():
Print (value)
(3) Key-value pair traversal:
For item in Dic.items ():
Print (item)
(4) Traversing by Element (item): #返回的是一个个键值对的元组形式
For Key,value in Dict.items ():
Print ("key=%s,value=%s"% (Key,value))
9. Dictionary Construction:
(1) Format cast: Dict ([]) or dict (a=1,b=2)
(2) Dictionary parsing: {x:x**2 for x in (2,3,4)}
10. Application of the dictionary:
(1) Nested processing of dictionaries more complex data structures
(2) Value for mapping (more powerful than arrays in C)
A Dictionary of Python courses