![](/img/trans.png)
[英]Python dictionary - dict.get() return value if dict value is None
[英]Python function that takes value from a dict and return full dictionary for the value
我正在嘗試編寫一個 function ,它采用給定鍵(User_ID)的值並返回該值的完整字典。 我知道這可能無需編寫 function 就可以實現,但作為初學者,我正在嘗試用函數來建立我的知識。
我的數據是一個字典列表,如下所示:
[
{
"User_ID":"Z000",
"DOB":"01.01.1960",
"State":"Oregon",
"Bought":["P1","P2"]
},
{
"User_ID":"A999",
"DOB":"01.01.1980",
"State":"Texas",
"Bought":["P5","P9"]
}
]
我寫了以下 function 但我意識到這僅適用於字典但我有一個字典列表。 如何使其獲取User_ID
值並返回完整的字典,包括User_ID
、 DOB
、 State
和Bought
。
def find_user(val):
for key, value in dict_1.items():
if val == key:
return value
return "user not found"
如果您真的想為此任務編寫 function,那么您的設計就在正確的軌道上,但需要修改以考慮到您有一個字典列表這一事實。 像這樣的東西可能會起作用:
def find_user(userid):
for user_dict in big_list_of_user_dictionaries:
if user_dict['User_ID'] == userid:
return user_dict
但是,您最好創建一個新字典,其中每個鍵都是用戶 ID,每個值都是您的用戶信息字典之一。 您可以使用 Python 的字典推導來快速制作這樣的字典:
user_dict = {d['User_ID'] : d for d in big_list_of_user_dictionaries}
然后,您可以通過在user_dict
中查找他們的 id 來找到任何用戶的用戶信息字典,如下所示:
print(user_dict['Z000'])
您想遍歷列表並將字典的UserID
與輸入的 UserID 進行比較:
def find_user(val):
for d in lsts:
if val == d['User_ID']:
return d
return "user not found"
然后
print(find_user('Z000'))
印刷
{'User_ID': 'Z000',
'DOB': '01.01.1960',
'State': 'Oregon',
'Bought': ['P1', 'P2']}
和
print(find_user('000'))
印刷
user not found
希望這段代碼對你有用。
def find_user(val):
for dict_key in l:
if dict_key["User_ID"] == val:
return dict_key
else:
return "User Not Found"
print(find_user("Z000"))
這里 l 是存儲所有字典的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.