Write a Python Program to Iterate Over Dictionaries Using for Loop

Python Program to Iterate Over Dictionaries Using for Loop

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn  Python programming concepts. You can learn Python language at your own speed and time. One can learn concepts of Python language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Iterate Over Dictionaries Using for Loop

Write a Python Program to Iterate Over Dictionaries Using for Loop

PROGRAM: Python Program to Iterate Over Dictionaries Using for Loop

/* Python Program to Iterate Over Dictionaries Using for Loop */

1: Access both key and value using items()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

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

Output

a juice
b grill
c corn

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

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

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

Output

a juice
b grill
c corn

3: Access both key and value using iteritems()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

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

Output

a juice
b grill
c corn

4: Return keys or values explicitly

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

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

for value in dt.values():
    print(value)
Output
a
b
c
juice
grill
corn

 
 
 

 

Leave a Reply

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