Home > Enterprise >  Search for item in list of dictionary
Search for item in list of dictionary

Time:02-01

So I have this params:

p = [{'quantity': 1}, {'args': {'id': 12345678, 'age': 12}}]

And I want to be able to search for quantity and get the value 1 or the args key and get its doctionary ({'id': 12345678, 'age: 12})

This is what I have try:

def search(name: str, params: list[dict]):
    try:
        return next((x[name] for x in params if x), None)
    except KeyError:
        return None

I case I search for the value of quantity:

search(name='quantity', params=p)

This return 1

But in case I want to value of args:

search(name='args', params=p)

This return None

CodePudding user response:

To fix this, change the code to:

def search(name: str, params: list[dict]):
    try:
        return next((x[name] for x in params if name in x), None)
    except KeyError:
        return None

Now when you search for the value of 'quantity', you will get 1:

search(name='quantity', params=p)

And when you search for the value of 'args', you will get the dictionary:

search(name='args', params=p)
  • Related