Python - Iterate Over Dictionaries

In this program, you will learn how to iterate over dictionaries.


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


    data = {'fruit1':'apple', 'fruit2':'pear', 'fruit3':'mango'}
    for key, value in data.items():
        print(key,value)

Output



    fruit1 apple
    fruit2 pear
    fruit3 mango

In this example, passing two variables key and values for iterate through dictionary items items(). Display the loop variables key and value.

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



    data = {'fruit1':'apple', 'fruit2':'pear', 'fruit3':'mango'}
    for key in data:
        print(key,data[key])
    
    

Output


    fruit1 apple
    fruit2 pear
    fruit3 mango
    

In this example, iterate through dictionary using a for loop. Display the loop variable key and value at key i.e dt[key].



The following topics can be useful to understand this program.



Related Tutorials