Home > other >  Python function that takes value from a dict and return full dictionary for the value
Python function that takes value from a dict and return full dictionary for the value

Time:01-11

I'm trying to write a function that takes a value for a given key (User_ID) and return the full dictionary for that value. I understand that this can probably be achieved without writing a function but as a beginner I'm trying to build my knowledge with functions.

My data is a list of dictionaries and looks like this:

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

I wrote the following function but I realized that this is would only work for a dictionary but I have a list of dictionaries. How can I make it to take the User_ID value and return the full dictionary including the User_ID, DOB, State and Bought.

def find_user(val):
    for key, value in dict_1.items():
         if val == key:
             return value
 
    return "user not found"

CodePudding user response:

If you really want to write a function for this task, your design is on the right track, but needs to be modified to account for the fact that you have a list of dictionaries. Something like this might work:

def find_user(userid):
    for user_dict in big_list_of_user_dictionaries:
        if user_dict['User_ID'] == userid:
            return user_dict

However, you might be better off creating a new dictionary, where each key is the userid, and each value is one of your user info dictionaries. You could use Python's dictionary comprehensions to make such a dictionary quickly:

 user_dict = {d['User_ID'] : d for d in big_list_of_user_dictionaries}

Then you could find the user info dictionary for any user by looking up their id in the user_dict, like this:

 print(user_dict['Z000'])

CodePudding user response:

You want to iterate over the list and compare the UserID of a dictionary with an input UserID:

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

Then

print(find_user('Z000'))

prints

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

and

print(find_user('000'))

prints

user not found

CodePudding user response:

Hope this code works for you.

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

here l is the list that stores all your dictionaries.

  •  Tags:  
  • Related