範例如下 :
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
for key,value in car.items(): # items()方法會讓for迴圈將每個鍵-值對分別存到key和value的變數中
print("key : "+key) # 印出鍵
print("value : "+value) # 印出值
輸出結果 :
key : color
value : black
key : brand
value : toyota
範例如下 :
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
for key in car.keys(): # keys()方法會讓for迴圈將每個鍵存到key變數中
print("key : "+key) # 印出鍵
輸出結果 :
key : color
key : brand
範例如下 :
car = {"color":"black","brand":"toyota"} # 建立一個car字典裡面包含兩個鍵值對
for value in car.values(): # values()方法會讓for迴圈將每個值存到value變數中
print("value : "+value) # 印出值
輸出結果 :
value : black
value : toyota
範例如下 :
favorite_fruits={"bonny":"apple","jack":"banana","rose":"grape","steven":"apple"} # 建立一個favorite_fruits字典裡面包含四個鍵值對
for key in sorted(favorite_fruits.keys()): # sorted()方法包住keys()方法會讓for迴圈將每個鍵依照字母順序排好存到key變數中
print(key) # 印出鍵
輸出結果 :
bonny
jack
rose
steven
範例如下 :
favorite_fruits={"bonny":"apple","jack":"banana","rose":"grape","steven":"apple"} # 建立一個favorite_fruits字典裡面包含四個鍵值對
print("the following fruits have been mentioned :")
for value in set(favorite_fruits.values()) : # set()方法包住keys()方法會讓for迴圈將不重複的值存到value變數中
print(value) # 印出值
輸出結果 :
the following fruits have been mentioned :
banana
apple
grape
範例如下 :
# 建立一個字典裡面包含兩個字典
pets={
"dog":{
"name":"Tony",
"age":4,
"gender":"male",
},
"cat":{
"name":"Kate",
"age":3,
"gender":"female",
},
}
for pet,pet_info in pets.items() : # items()方法會讓for迴圈將每個鍵-值對分別存到pet和pet_info的變數中
print("I have a "+pet+",its name is "+pet_info["name"]+","
+str(pet_info["age"])+" years old,and gender is "+pet_info["gender"] ) # 分別取得鍵(dog,cat)和從字典中的字典取得值
輸出結果 :
I have a dog,its name is Tony,4 years old,and gender is male
I have a cat,its name is Kate,3 years old,and gender is female
範例如下 :
colors={"orange":["red","yellow"],"green":["blue","yellow"]} # 建立一個colors字典裡面有兩個鍵值對
for keys,values in colors.items() : # items()方法會讓for迴圈將每個鍵-值對分別存到keys和values的變數中
print("If you want to get color "+keys)
print("you need to add :")
for value in values: # 告知python從values串列中取出值,並將取出的值存到value變數內
print(value)
輸出結果 :
If you want to get color orange
you need to add :
red
yellow
If you want to get color green
you need to add :
blue
yellow
附上排版較優美的
HackMD網址 : https://hackmd.io/i3eIlj2jR5GVx9Ui1jAb7A
資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯
您好,想請問為什麼下面這行需要加號才能成功呢? 謝謝
例如 “+pet+” 還有 +pet_info["gender"]
print("I have a "+pet+",its name is "+pet_info["name"]+"," +str(pet_info["age"])+" years old,and gender is "+pet_info["gender"] )
因為 pet 是變數,但是 "I have a " 屬於字串
我們是要取 pet 的值而不是用pet這個名稱 ,所以用+去獲得該變數的值
了解了! 感謝回覆。另外想請問為什麼 PET 是前後有加號,但是 PET_INFO 只有前面有加號呢?
那是作者換行的關係?實際上前後還是兩個+
如果你說的是 + pet_info["gender"],這段的話因為後面沒有要連接的字串,所以只需要前面一個 + 就好,用這張圖來和不知道會不會比較好懂?