This article mainly introduces the dictionary traversal operation implemented by Python3, and analyzes the related operating techniques of Python3 for dictionary keys, key values and key-value pair traversal in the form of examples. Friends who need it can refer to it
The example in this article describes the Python3 dictionary traversal operation. Share it with everyone for your reference, as follows:
Dictionary is a data type provided for non-sequence collections.
The process of finding value information in a set through any key is called mapping. Python implements mapping through a dictionary.
Assign values to the dictionary:
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> print(d) {1: 123, 'list': [1, 2, 3], '111': 'python3', 'tuple': (4, 5, 6)}
The above statement illustrates the order of the items in the dictionary and the order of assignment There may be inconsistencies, i.e. the dictionary is unordered.
There are several types of dictionary traversal:
1. Traverse the keys of the dictionary
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d: print(str(key)+':'+str(d[key])) list:[1, 2, 3] 1:123 111:python3 tuple:(4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d.keys(): print(key) 1 list 111 tuple
2. Traverse the values of the dictionary value
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for value in d.values(): print (value) [1, 2, 3] 123 python3 (4, 5, 6)
3. Traverse the items of the dictionary
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for item in d.items(): print(item) ('list', [1, 2, 3]) (1, 123) ('111', 'python3') ('tuple', (4, 5, 6))
4. Traverse the key-value of the dictionary
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key,value in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for (key,value) in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
The running effect of the above example is as shown below:
Related recommendations:
Python3 implements the shopping cart function
Python3 implements the QQ email function (text)_python
The above is the detailed content of Detailed explanation of dictionary traversal operation implemented in Python3. For more information, please follow other related articles on the PHP Chinese website!