0

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

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
Ran Pol
  • 85
  • 7

1 Answers1

1

I have a set of functions that you could use for this [ getNestedVal(p, 'args') would return {'id': 12345678, 'age: 12} ]...or you can use this generator

def yieldNestedVals(obj, key):
    if isinstance(obj, str): return
    try: yield obj[key]
    except: pass
    if isinstance(obj, dict): obj = obj.values()
    for i in (obj if hasattr(obj, '__iter__') else []):
        for v in yieldNestedVals(i, key): yield v

inside search like

def search(name, params, defaultVal=None):
    for v in yieldNestedVals(params, name): return v # return 1st generated value
    return defaultVal # if nothing if generated

[ Ofc you can omit both the defaultVal parameter and the last line if you want to just return None when nothing if found, since that is the default behavior when a function doesn't come across a return statement. ]

Now search('args', p) should also return {'id': 12345678, 'age: 12} and you can try it with other keys as well:

# p = [{'quantity': 1}, {'args': {'id': 12345678, 'age': 12}}]
{k: search(k, p) for k in ['quantity', 'args', 'id', 'age', 'dneKey']}

would return

{'quantity': 1,
 'args': {'id': 12345678, 'age': 12},
 'id': 12345678,
 'age': 12,
 'dneKey': None}
Driftr95
  • 4,572
  • 2
  • 9
  • 21