How to iterate dictionaries using for loops in Python


With for loops, we can iterate a dictionary by key, value or both of them:

By key:

>>> d = {'a':12, 'b':2, 'c':21}

>>> for key in d:

print(key, end=' ')


a b c 

>>

By value:

>>> for value in d.values():

print(value, end=' ')


12 2 21 

>>> 

By both key and value:

>>> for key, value in d.items():

print(key+ ":"+ str(value))


a:12

b:2

c:21

>>> 

Caveat, please check the following code:

>>> for key in d:

print(key + ':' + str(d[key]))


a:12

b:2

c:21

>>> 

It does the same thing as the d.items() code, but d[key] inside a for loop caused the keys to be hashed again, which is not efficient if the dictionary is large.

Comments

Popular posts from this blog

How to create a memory puzzle game with Python and Pygame (#005)

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

Introduction to multitasking with Python #003 gevent (2020 tutorial)