Home > other >  Return Dictionary from a list using username
Return Dictionary from a list using username

Time:12-24

I created a function to return dictionary object. I can't call it with the username but get the following error: 'TypeError: list indices must be integers or slices, not str'

def find_user(df_dict, filter_string):
    filtered_dict = dict(filter(lambda item: filter_string in item[0], df_dict.items()))

    return filtered_dict

find_user(df_dict=reviewers_dicts['Username'], filter_string='krpz1113')

CodePudding user response:

There are couple of things wrong here:

  1. reviewers_dicts['Username'] gives you a string "bkpn1412" and it doesn't have .items() attribute.
  2. You want to check the filter_string against the "Username" key in the dictionary not checking if the dictionary has filter_string.
  3. As your function's name suggest, you want to find a user, not getting a list/dict of users(presumably usernames are unique.)

Here is the solution:

def find_user(list_of_dicts, filter_string):
    for d in list_of_dicts:
        if d["Username"] == filter_string:
            return d


reviewers_dicts = [
    {
        "Username": "bkpn1412",
        "DOB": "31.07.1983",
        "State": "Oregon",
        "Reviewed": ["cea76118f6a9110a893de2b7654319c0"],
    },
    {
        "Username": "krpz1113",
        "DOB": "21.17.1989",
        "State": "Oregon",
        "Reviewed": ["jh5b34jh5b3jh5b34jh5b3hj5b3b5jh34"],
    },
]
print(find_user(list_of_dicts=reviewers_dicts, filter_string="krpz1113"))
  • Related