Python How to loop a dictionary

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

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

上一篇: Python How to delay few seconds
下一篇: Java Check if key exists in HashMap
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号