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 the Author

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

Comments

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
ImanPython – How to loop a List Recent comment authors
newest oldest most voted
Iman
Guest
Iman

good example, thanks.

trackback
Python – How to loop a List

[…] Python – How to loop a dictionary […]