一起使用Python里for循環和dictionary字典


1.先定義一個字典的內容

 1 i=
 2 {  3         'status': 'success',  4          'country': '中國',  5          'countryCode': 'CN',  6          'region': 'BJ'
 7 }

2.打印字典看看

1 i=
2 { 3        'status': 'success', 4         'country': '中國', 5        'countryCode': 'CN', 6         'region': 'BJ'
7 } 8 print(i)

 

 

3.如果直接運用FOR循環,那么只會把關鍵詞顯示出來,里面的值不會顯示

1 i={ 2        'status': 'success', 3         'country': '中國', 4        'countryCode': 'CN', 5         'region': 'BJ'
6 } 7 for a in i: 8     print(a)

 

4.在字典后加.values()可以顯示值,但是不顯示關鍵詞

1 i={ 2        'status': 'success', 3         'country': '中國', 4        'countryCode': 'CN', 5         'region': 'BJ'
6 } 7 for a in i.values(): 8     print(a)

 

5.在字典后加.items()可以同時顯示關鍵詞和值

1 i={ 2        'status': 'success', 3         'country': '中國', 4        'countryCode': 'CN', 5         'region': 'BJ'
6 } 7 for a in i.items(): 8     print(a)

 

6 .最好的方法還是加上key,value這樣可以顯示更多東西

1 i={ 2        'status': 'success', 3         'country': '中國', 4        'countryCode': 'CN', 5         'region': 'BJ'
6 } 7 for key,value in i.items(): 8     print("IP信息:"+str(key)+" is "+str(value))

 

7.如果只是字符串就可以單單這樣顯示即可

1 i={ 2        'status': 'success', 3         'country': '中國', 4        'countryCode': 'CN', 5         'region': 'BJ'
6 } 7 for key,value in i.items(): 8     print("IP信息:"+key+" is "+value)

 

 

參加文檔:https://jingyan.baidu.com/article/636f38bb9b152dd6b8461025.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM