How to iterate over a dictionary (keys and values) in python using a for loop ?

Active August 06, 2021    /    Viewed 4225    /    Comments 0    /    Edit


Examples of how to terate over a dictionary in python using a for loop:

Create a dictionary

Lets first create a simple dictionary in python (as a reminder, a dictionary is made up of a set of key and value):

>>> d = {'a':1,'b':2,'c':3}
>>> type(d)
<class 'dict'>

Iterate over dictionary keys

To iterate over the keys of a dictionary, a solution is to do:

>>> for key in d:
...     print(key)
...

returns here

a
b
c

Iterate over dictionary keys and values.

Dictionary d defined above has 3 keys: a,b and c. To iterate over the keys and associated value a solution in python 3 is to do:

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

returns

a 1
b 2
c 3
>>>

Note: in python 2 the syntax was a little bit different (iteritems() instead of items()):

>>> for key, value in d.iteritems():
...     print(key,value)
...

returns

a 1
b 2
c 3
>>>

Iterate over dictionary keys and iterable values (such as dictionary or list)

Another example, with a dictionary with a key linked to another sub dictionary:

Pour des dictionnaires plus complexes avec des valeurs qui sont itérables comme un dictionnaire ou une liste par exemple il est aussi possible de créer une boucle qui affiche les données imbriquées, exemple:

>>> d = {'a':1,'b':2,'c':{'hello':1,'Bonjour':2}}

then to iterate over the dictionary a solution is to:

>>> for key, value in d.items():
...     if isinstance(value, dict):
...             for sub_key, sub_value in value.items():
...                     print(key,sub_key,sub_value)
...     else:
...             print(key,value)

returns

a 1
b 2
c hello 1
c Bonjour 2

Big dictionary: Iterate only over the first n elements

Let's assume we have a very large dictionary in python:

d = {}

for i in range(1000000):
    d[i] = random.randint(1,10)

and that we want to print only the first n elements.

A solution is then to use islice,

from itertools import islice

for item in islice(d.items(), 5):
    print('Key:{} Value:{}'.format(item[0], item[1]))

returns

Key:0 Value:1
Key:1 Value:7
Key:2 Value:10
Key:3 Value:7
Key:4 Value:8

Note: islice can be used to slice any part of the dictionary islice(dict,start, end):

from itertools import islice

for item in islice(d.items(), 10,15):
    print('Key:{} Value:{}'.format(item[0], item[1]))

returns

Key:10 Value:3
Key:11 Value:1
Key:12 Value:4
Key:13 Value:8
Key:14 Value:10

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount