Python How to loop a dictionary
By:Roy.LiuLast updated:2019-08-17
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
From:一号门
Previous:Python How to delay few seconds
COMMENTS