Python Program to Iterate Over Dictionaries Using for Loop – 2024

Hey guys, in this blog we will see a Python Program to Iterate Over Dictionaries Using for Loop.

Example 1: Access both key and value using items()

# Python Program to Iterate Over Dictionaries Using for Loop

dt = {'a': 'messi', 'b': 'ronaldo', 'c': 'neymar'}

for key, value in dt.items():
    print(key, value)

Output

a messi
b ronaldo
c neymar
  • Here we have used dt.items() which will print [(‘a’,’messi’),(‘b’,’ronaldo’),(‘c’,’neymar’)].
  • And then we are simply every element of the list in a new line.

Example 2: Access both key and value without using items()

# Python Program to Iterate Over Dictionaries Using for Loop

dt = {'a': 'messi', 'b': 'ronaldo', 'c': 'neymar'}

for key in dt:
    print(key, dt[key])

Output

a messi
b ronaldo
c neymar
  • Here we are traversing in the keys of our dictionary.
  • Keys of our dictionary are a,b,c.
  • Then we are simply printing Keys and their corresponding values in the dictionary.

Example 3: Access both key and value using iteritems() (only for python 2)

# Python Program to Iterate Over Dictionaries Using for Loop

dt = {'a': 'messi', 'b': 'ronaldo', 'c': 'neymar'}

for key, value in dt.iteritems():
    print(key, value)

Output

a messi
b ronaldo
c neymar
  • We are using dt.iteritems() to access both keys and values of our dictionary.

Example 4: Return keys or values explicitly

# Python Program to Iterate Over Dictionaries Using for Loop

dt = {'a': 'messi', 'b': 'ronaldo', 'c': 'neymar'}

for key in dt.keys():
    print(key)

for value in dt.values():
    print(value)

Output

a
b
c
messi
ronaldo
neymar
  • Here we are first printing all the keys using dt.keys() method.
  • And similarly, we are the printing values using dt.values().

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *