[Python] dictionary traversal (dict traversal)

       Dictionaries are also the type we often use when doing data analysis. Xiaobai has summarized the traversal of DataFrame before. In this blog post, Xiaobai has sorted out several methods for traversing dictionaries.

      As we all know, a dictionary is a combination of key-value pairs, so the traversal of the dictionary naturally includes the traversal of keys and values. The following will introduce the traversal of three cases of traversing keys, values, and key values.

First, create a dictionary for the following traversal.

  1. dict = {
  2. 'Xiao Ming' : 129 ,
  3. 'Xiaolan' : 148 ,
  4. 'Little Red' : 89
  5. }

1. Traverse key

It can be seen that there are three methods for traversing the key value of the dictionary, and the third method reports an error, because Xiaobai uses the PY3 version, and the keys() method in python3 replaces the iterkeys() method. It is possible to use the python2 version, but Xiaobai recommends mastering the methods in python3. After all, python2 will be used less and less.

  1. # function1
  2. for key in dict:
  3. print (key)
  4. ---------------result---------------------
  5. Xiao Ming
  6. Xiaolan
  7. little red
  8. #function2
  9. for key in dict.keys():
  10. print (key)
  11. ---------------result---------------------
  12. Xiao Ming
  13. Xiaolan
  14. little red
  15. #function3
  16. for key in dict.iterkeys():
  17. print (key)
  18. ---------------result-----------------------
  19. AttributeError Traceback (most recent call last)
  20. <ipython-input-10-e1bc6c7e42fe> in <module>
  21. 1
  22. 2 #Method three
  23. ----> 3 for key in dict.iterkeys():
  24. 4 print (key)
  25. AttributeError: 'dict' object has no attribute 'iterkeys'

2. Traverse the value

Similarly, the reason for the error in the second method is the same. The second method is removed in python3 and replaced by method 1. Here, traversing the value is not the same as traversing the key. There is nothing like the first method when traversing the key. , the first method of traversing the key, the default output is the key

  1. # function1
  2. for value in dict.values():
  3. print (value)
  4. ------------------------
  5. 129
  6. 148
  7. 89
  8. #function2
  9. for value in dict.itervalues():
  10. print (value)
  11. -----------------------------
  12. AttributeError Traceback (most recent call last)
  13. <ipython-input-12-92a1ef0f19df> in <module>
  14. ----> 1 for value in dict.itervalues():
  15. 2 print (value)
  16. AttributeError: 'dict' object has no attribute 'itervalues'

3. Traverse key and value at the same time

There are many ways to traverse at the same time, let's take a look at them one by one:

(1) First look at method 1 and method 2. In fact, these two methods are similar, but the difference between adding or not adding parentheses can be selected according to preference.

(2) Then look at method 3. Method 3 uses shorthand to realize the reading of key and value, which is simpler in form

(3) Look at the two methods used in combination with zip. In fact, method four is more like methods one and two, but there is one more zip operation. Method five is more like method three, which also uses the zip function.

Note: In addition, let's take a look at the difference between the key, value method and kv method. In methods 4 and 5, Xiaobai outputs the type of data. The difference between the two methods mainly lies in the data type of the output data, key, The value method outputs the value itself, what type of data is, and what type is the result, but the tuple type output by method five.

  1. # function1
  2. for key,value in dict.items():
  3. print ('key: ',key,'value: ',value)
  4. ------------------------
  5. key: Xiao Ming value: 129
  6. key: Xiaolan value: 148
  7. key: Xiaohong value: 89
  8. #function2
  9. for (key,value) in dict.items():
  10. print ('key: ',key,'value: ',value)
  11. ------------------------
  12. key: Xiao Ming value: 129
  13. key: Xiaolan value: 148
  14. key: Xiaohong value: 89
  15. #function3
  16. for kv in dict.items():
  17. print ('kv is : ',kv)
  18. ------------------------
  19. kv is : ( 'Xiao Ming' , 129 )
  20. kv is : ( 'Xiao Lan' , 148 )
  21. kv is : ( 'Little Red' , 89 )
  22. ----------------------Use with zip ----------------------
  23. #function4
  24. for key,value in zip(dict.keys(), dict.values()):
  25. print ('key:',key,'value: ',value)
  26. print('type key:',type(key),'type value:',type(value))
  27. ------------------------
  28. key: Xiao Ming value: 129
  29. type key: <class 'str'> type value: <class 'int'>
  30. key: Xiaolan value: 148
  31. type key: <class 'str'> type value: <class 'int'>
  32. key: Xiaohong value: 89
  33. type key: <class 'str'> type value: <class 'int'>
  34. #function5
  35. for kv in zip(dict.keys(), dict.values()):
  36. print ('kv: ',kv)
  37. print('type:',type(kv))
  38. ------------------------
  39. kv: ( 'Xiao Ming' , 129 )
  40. type: <class 'tuple'>
  41. kv: ( 'Xiaolan' , 148 )
  42. type: <class 'tuple'>
  43. kv: ( 'Little Red' , 89 )
  44. type: <class 'tuple'>

4. Define methods to read key and value

The method for reading key and value is described above. Then, if we want to read key and value in a project, we should define it as a method to read and output the result, which is convenient for our call and subsequent use, as follows:

  1. #Define the function to read the key value
  2. def keys_function(dict):
  3. keys = []
  4. #read key
  5. for k in dict.keys():
  6. keys.append(format(k))
  7. return keys
  8. #Define read value
  9. def values_function(dict):
  10. values = []
  11. for v in dict.values():
  12. values.append(format(v))
  13. return values
  14. print('key:',keys_function(dict),'type:',type(keys_function(dict)))
  15. ------------result--------------
  16. key: [ 'Xiao Ming' , 'Xiao Lan' , 'Xiao Hong' ] type : < class 'list' >
  17. print('value:',values_function(dict),'type:',type(values_function(dict)))
  18. ------------result--------------
  19. value: ['129', '148', '89'] type: <class 'list'>

 

Tags: [Python] dictionary traversal (dict traversal)

technology analyze The advanced path of Python Xiaobai Python

Related: [Python] dictionary traversal (dict traversal)