繁体   English   中英

Python function 从字典中获取值并返回该值的完整字典

[英]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_IDDOBStateBought

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM