Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize the traversal of Dictionary by Python

Shulou Source: shulou.com Published: 2022-06-01 13:44:40 09月28日 Update

This article mainly introduces Python how to achieve dictionary traversal, the article is very detailed, has a certain reference value, interested friends must read it!

The traversal dictionary is mainly about traversing the entries, keys, and values of the dictionary. The key of traversing the dictionary is to list all the items contained in the dictionary, and the key and value of traversing the dictionary is to list all the keys and values of the dictionary. The items method provided by the dictionary gets the collection of all the items in the dictionary, and the items method can be used in the for loop statement to traverse all the items contained in the dictionary.

Traversing with for

Similar to other data structures, we can use for to traverse elements.

Dict_= {'key1':'value1','key2':'value2'} for i in dict_: print (I, end='\ t') for i in dict_: print (dict_ [I], end='\ t')

The first traversal takes the key, the second traversal takes the value

The output is

Key2 key1value2 value1 traverses the keys and values of the dictionary

Using keys, values can return iterations of all values of a dictionary

Dict_= {'key1':'value1','key2':'value2'} for key in dict_: print (key, end='\ t') for value in dict_.values (): print (value, end='\ t')

Running result:

Key2 key1value2 value1 traverses entries in the dictionary

Using items, you can convert the dictionary type to the corresponding tuple list, and then traverse the dictionary.

Dict_= {'key1':'value1','key2':'value2'} item=dict_.items () print (item) for key,value in item: print (key,value)

The results are as follows:

Dict_items ([('key2','value2'), (' key1','value1')]) key2 value2key1 value1 above is all the content of the article "how to traverse the dictionary by Python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Dictionaries results content methods articles values elements interests guys buddies data data structures more knowledge types structures industries sentences information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information Microsoft macOS Linux