Simple way to loop through dictionary elements in Python

高洛峰
Release: 2017-02-23 11:47:29
Original
2095 people have browsed it

The following editor will bring you a simple method of looping through dictionary elements in python. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

A simple for statement can loop through all the keys of the dictionary, just like processing sequences:


In [1]: d = {'x':1, 'y':2, 'z':3}

In [2]: for key in d:
  ...:   print key, 'corresponds to', d[key]
  ...: 
y corresponds to 2
x corresponds to 1
z corresponds to 3
Copy after login


Before python2.2, you could only use dictionary methods such as beys to obtain keys (because direct iteration of the dictionary was not allowed). If you only need values, you can use d.values ​​instead of d.keys. The d.items method will return key-value pairs as tuples. One of the great benefits of the for loop is that you can use sequence unpacking in the loop:


In [4]: for key, value in d.items():
  ...:   print key, 'corresponds to', value
  ...: 
y corresponds to 2
x corresponds to 1
z corresponds to 3
Copy after login


Note: The order of dictionary elements is usually not defined. In other words, when iterating, the keys and values ​​in the dictionary are guaranteed to be processed, but the processing order is uncertain. If order is important, you can save the key values ​​in a separate list, for example to sort before iterating.

The above simple method of python looping through dictionary elements is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more related articles on the simple method of python looping through dictionary elements, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!