我在字典中給出了一些值和鍵,并顯示了這里存在的兩個鍵的值。
def save_user_1(**user):
return user["id"], user["mail"]
print(save_user_1(id = 1, name = "john", mail = "[email protected]"))
輸出:(1,'[email protected]')
1.為什么在這里將輸出顯示為元組?
2.如何在這里獲取鍵的值?(與輸出中顯示的相反)
uj5u.com熱心網友回復:
- 要獲取串列作為輸出,請使用括號:
return [user["id"], user["mail"]] - 您可以嘗試
user.keys()獲取字典鍵,或user.items()同時獲取鍵和值:
def save_user_1(**user):
print('user keys', user.keys())
for key, value in user.items():
print("key =", key, ", value =", value)
return user["id"], user["mail"]
print(save_user_1(id = 1, name = "john", mail = "[email protected]"))
輸出 :
user keys dict_keys(['id', 'name', 'mail'])
key = id , value = 1
key = name , value = john
key = mail , value = [email protected]
(1, '[email protected]')
uj5u.com熱心網友回復:
- 因為
user["id"], user["mail"]是一個元組,與(user["id"], user["mail"]). - 您正在獲取鍵
'id'和的值'mail'。如果你想要鑰匙(我不知道你為什么要),你可以return [k for k in ('id', 'mail') if k in user].
uj5u.com熱心網友回復:
當你這樣做時,return user["id"], user["mail"]你是在告訴 python 回傳一個元組。您能否在您的問題中添加您想要什么樣的輸出print?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437564.html
上一篇:如何從特定行和列中找到最常見的單詞并列出它在data.csv中出現的頻率?[復制]
下一篇:不好:FastApi回應問題
