This article brings you a summary of dictionary operations in python (six types). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The dictionary is represented by {}, which is a series of "key-value" pairs. You can use the key to access the corresponding value. This value can be a number, a string, or anything. python object. Keys and values are separated by colons
, and key-value pairs are separated by commas. For example: A={'color': 'red', 'points': 10}
1. To access the dictionary value
, just specify the dictionary name and key of the dictionary.
A={'a':7,'b':'happy'} print(A['a']) >>>7
2. Add key-value pairs
A={'a':7,'b':'happy'} A['c']=8 print(A) >>>{'a': 7, 'b': 'happy', 'c': 8}
3. Modify the value of the key
A={'a':7,'b':'happy'} A['a']=8 print(A) >>>{'a': 8, 'b': 'happy'}
4. Delete key-value pairs
A={'a': 7, 'b': 'happy', 'c': 8} del A['c'] print(A) >>>A={'a':7,'b':'happy'}
5. Traverse the dictionary
The x and y can be changed according to the actual situation to make it easier to read.
book={ 'number':'0', 'name':'从入门到放弃', 'author':'XXX', } for x, y in book.items(): #1、同时取键值对 print(x+':'+y) for x in book.keys(): #2、只取键 print(x) for x in book.values(): #3、只取值 print(x)
When only taking the value, all the values in the dictionary are extracted, and duplicate values are not considered. If you need a list with non-duplicate values, you can use set(), which will automatically remove duplicates. item.
for x in set(book.values()): print(x)
6. Nesting
Lists and dictionaries can be nested in dictionaries, depending on the situation.
The above is the detailed content of Summary of dictionary operations in python (six types). For more information, please follow other related articles on the PHP Chinese website!