Py学习  »  Python

Python函数,它从dict中获取值并返回值的完整字典

elideli • 3 年前 • 1314 次点击  

我试图编写一个函数,为给定的键(User_ID)获取一个值,并返回该值的完整字典。我知道这可能不需要编写函数就可以实现,但作为一名初学者,我正试图用函数来构建我的知识。

我的数据是一个字典列表,如下所示:

[
   {
      "User_ID":"Z000",
      "DOB":"01.01.1960",
      "State":"Oregon",
      "Bought":["P1","P2"]
   },
   {
      "User_ID":"A999",
      "DOB":"01.01.1980",
      "State":"Texas",
      "Bought":["P5","P9"]
   }
]

我编写了以下函数,但我意识到这只适用于字典,但我有一个字典列表。我怎样才能赶上火车呢 User_ID 值并返回包含 用户ID , DOB , State Bought .

def find_user(val):
    for key, value in dict_1.items():
         if val == key:
             return value
 
    return "user not found"
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131993
 
1314 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Vicky Singh
Reply   •   1 楼
Vicky Singh    3 年前

希望这段代码对你有用。

 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"))

这是你所有字典的清单。

Andrew Merrill
Reply   •   2 楼
Andrew Merrill    3 年前

如果您真的想为此任务编写函数,那么您的设计是正确的,但需要进行修改,以考虑到您有一个字典列表这一事实。类似的方法可能会奏效:

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}

然后,您可以通过在数据库中查找用户id来查找任何用户的用户信息字典 user_dict ,就像这样:

 print(user_dict['Z000'])
enke
Reply   •   3 楼
enke    3 年前

您希望迭代列表并比较 UserID 使用输入用户ID创建字典:

def find_user(val, lsts):
    for d in lsts:
        if val == d['User_ID']:
            return d
    return "user not found"

然后

print(find_user('Z000', lsts))

印刷品

{'User_ID': 'Z000',
 'DOB': '01.01.1960',
 'State': 'Oregon',
 'Bought': ['P1', 'P2']}

print(find_user('000', lsts))

印刷品

user not found

但是,如果您的数据如下所示:

d = { "Data": [{"User_ID":"Z000"},{"User_ID":"A999"} ]}

然后可以将字典中的列表传递给函数,如:

find_user('Z000', d['Data'])

它回来了

{'User_ID': 'Z000'}