Main Tutorials

Python – How to loop a dictionary

In this tutorial, we will show you how to loop a dictionary in Python.

1. for key in dict:

1.1 To loop all the keys from a dictionary – for k in dict:


    for k in dict:
	    print(k)

1.2 To loop every key and value from a dictionary – for k, v in dict.items():


    for k, v in dict.items():
	    print(k,v)

P.S items() works in both Python 2 and 3.

2. Python Example

Full example.

test_dict.py

def main():
    stocks = {
        'IBM': 146.48,
        'MSFT':44.11,
        'CSCO':25.54
    }
    
    #print out all the keys
    for c in stocks:
        print(c)
    
    #print key n values
    for k, v in stocks.items():
        print("Code : {0}, Value : {1}".format(k, v))
    
if __name__ == '__main__':
    main()

Output


MSFT
IBM
CSCO
Code : MSFT, Value : 44.11
Code : IBM, Value : 146.48
Code : CSCO, Value : 25.54

P.S Tested with Python 2.7.10 and 3.4.3

References

  1. Python 2 – data structure – dictionaries
  2. Python 3 – data structure – dictionaries

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Iman
6 years ago

good example, thanks.