Python – How to loop a dictionary
来源:互联网 发布:美国圣劳伦斯学院知乎 编辑:程序博客网 时间:2024/06/05 18:48
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
MSFTIBMCSCOCode : MSFT, Value : 44.11Code : IBM, Value : 146.48Code : CSCO, Value : 25.54
P.S Tested with Python 2.7.10 and 3.4.3
0 0
- Python – How to loop a dictionary
- How To Loop A Map In Java
- How to quickly look up a word in dictionary
- How to use an ActiveX script task to create a loop in DTS
- How to list files in a dictionary modified after a specific date
- Python: How to Sort a List
- How to become a proficient Python programmer
- Python: How to Sort a List
- How to become a proficient Python programmer
- python : Sorting a Dictionary
- how to manage swift3 i-- loop
- python how to write unicode to a txt file
- how to install dictionary in ubuntu.
- How to Run a Python Script Without Python
- Python-make a sorted dictionary
- Python入门读物摘要--How to think like a csor
- How-to-configure-emacs-as-a-Python-IDE
- How to Get a List of Class Attributes in Python
- rtmp中文手册
- Android--Telephony
- Linux swap分区
- Xcode7.0上面使用http进行请求错误
- jmeter(二) 优缺点
- Python – How to loop a dictionary
- Android中实现第三方分享
- MongoDB数据库设计中6条重要的经验法则(二)
- Android之Telephony各文件解释
- ubuntu下安装cscope插件
- new一个类对象和使用类名创建一个对象有什么区别?
- matplotlib简介
- UITableView下拉刷新
- UIViewContentMode各种模式的样式