0

I want to output all the dictionary items in a list that contain a partial query on one of it's keys.

Considering this question, I want to achieve something similar but, from the following list:

people = [
{"name": "Pamela", "age": 9}
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

Searching for "Pam", I want to get both of these entries:

{"name": "Pamela", "age": 9},
{"name": "Pam", "age": 7}

Since I would like to search for different keys in the dictionary, based on user preference, I think this is the best solution I find in the mentioned thread:

def search(db, key, value):
    for item in db:
        if value in item[key]: # This is the line i'm having trouble with
            return item

However, the command print(search(people, 'name', 'Pam')) will only output {"name": "Pam", "age": 7}

Hugo
  • 89
  • 1
  • 6

1 Answers1

0

I'm sorry, I think I found a solution. The function was indeed getting both results but return item was only returning the last item viewed by the for loop and, as expected, the print statement only showed that. Here is the code I'm using if someone is having the same problem:

def search(db, key, value):
    result = []
    for item in db:
        if value in item[key]:
            result.append(item)

It's just a matter of instantiating an empty list and appending to it the items that pass. I feel a bit dumb and proud at the same time now.

Hugo
  • 89
  • 1
  • 6