[英]Want to make dictionary key inputted by user in a python function argument
def build_profile(f_name,l_name,**qualification):
profile={}
profile['first']=f_name
profile['last']=l_name
for k,v in qualification.items():
profile[k]=v
return profile
pl=[]
while True:
pl.append(build_profile(input("Enter first name: "),\
input("Enter last name:"),graduation=input("Enter Subject:"),\
masters=input("Enter Subject:")))
if input("Want to finish?(Y/N) ").upper()=="Y":
break
print(pl)
給定的函數接受用戶輸入的“畢業”和“碩士”鍵值,但我認為對於不同的用戶,教育水平可能不同,有些可能是博士,有些甚至可能沒有完成高中。 我試圖將字典“限定”的鍵值轉換為由用戶輸入,但每當我轉換
graduation=input("Enter Subject:")
到
input("Enter value:")=input("Enter Subject:")
我收到錯誤“關鍵字不能是表達式”。 在互聯網上搜索我知道 python 中的 split() 函數可以完成它,但我無法讓它在我的代碼中工作。
#SOLVED 根據答案,我修改了我的代碼如下,現在它可以按我的意願工作:
def build_profile(f_name,l_name,qualification):
profile={}
profile['first']=f_name
profile['last']=l_name
for k,v in qualification.items():
profile[k]=v
return profile
pl=[]
while True:
first_name=input("first name: ")
last_name=input("last name: ")
no_of_qual=int(input("How many qualification you want to add?"))
dict_qual={}
for qual in range(no_of_qual):
dict_qual[input("Enter subject")]=input("Enter qualification")
inv_qual = {v: k for k, v in dict_qual.items()}
pl.append(build_profile(first_name,last_name,inv_qual))
if input("Want to add more users?(Y/N) ").upper()=="N":
break
print(pl)
您正在嘗試使用字符串作為參數名稱,這是不可能的。 輸入實際字典可能比使用 ** 參數更好:
def build_profile(f_name: str, l_name: str, qualification: dict) -> dict:
return {'first': f_name, 'last': l_name, **qualification}
pl=[]
while True:
pl.append(build_profile(input("Enter first name: "), \
input("Enter last name: "), \
{input("Enter value: "):input("Enter subject: ")}))
if input("Want to finish? (Y/N) ").upper() == "Y":
break
print(pl)
它要求一個值,然后是一個主題(僅一次)。
您可能想要的不是為不同的人使用不同的鍵,而是添加一個鍵,例如“級別”,您可以使用您要求的不同值(如 PHD)。 那么它看起來像這樣:
def build_profile(f_name,l_name,**qualification):
profile={}
profile['first']=f_name
profile['last']=l_name
for k,v in qualification.items():
profile[k]=v
return profile
pl=[]
while True:
pl.append(build_profile(input("Enter first name: "),\
input("Enter last name:"),graduation=input("Enter Subject:"),\
masters=input("Enter Subject:"),\
level=input("Enter the level"))
if input("Want to finish?(Y/N) ").upper()=="Y":
break
print(pl)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.