How To Loop and Iterate Over Python Dictionary?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/loop-iterate-python-dictionary/
PINTEREST
PINTEREST
INSTAGRAM

Dictionaries provides simple data types with value and key. Dictionary data may be used in an iteration with for loop. By using for we can iterate over dictionary elements easily. In this tutorial we will look different ways to iterate over dictionary elements.

Example Dictionary

We will use following dictionary type named mydict in this tutorial.

Example Dictionary

Example Dictionary

Iterate with Implicit Iterator

Python dictionary type provides iterator interface where it can be consumed by for loops. We just need to provide the dictionary in for loop. This is shorter implementation of iterate with keys where we do not need to call iterkeys . In this example we will iterate over with keys in mydict dictionary.

Iterate with Iterator 

Iterate with Iterator 

Iterate with Keys

Like previous example we can specify the iterate keys with keys() function of dictionary. keys() function will return all keys inside given dictionary as python list than this list will be iterated with for loop.

Iterate Keys and Values

We can use functions provided by dictionary data type which will populate both keys and dictionaries in the same step of for loop. We will use items() function which will populate key and value in the same step. We will populate keys into k variable and values into v variable in each step.

Iterate Keys and Values 

Iterate Keys and Values 

Iterate Only Values

We can only iterate over values without using any key. We will use values() function provided by dictionary type which will populate values in given dictionary in an iterable format. We will put values of dictionary in each step into variable v .

LEARN MORE  How to Install Pip in Debian, Ubuntu, Kali

Iterate Only Values

Iterate Only Values

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/loop-iterate-python-dictionary/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)