user14187369
user14187369

Reputation:

How to dynamically create a return statement in python

My dictionary was below

I am searching inside a dictionary for dictionary below

test=[ { 'id': '1', 'name': 'A', 'businessArea': [ 'Accounting' ], 'Role': [ 'Developer' ], 'Designation': [ 'L2' ] }, { 'id': '2', 'name': 'B', 'businessArea': [ None ], 'Role': [ 'None' ], 'Designation': [ 'None' ] }, { 'id': '3', 'name': 'C', 'businessArea': [ 'Engineering' ], 'Role': [ 'Tester', 'Developer' ], 'Designation': [ 'L1' ] } ]

My code is working fine for below and returning only one

def contains(item, field, values):
    if field:
        item = item.get(field)     
    if item is None:
        return None                
    if isinstance(item, str):
        return item in values       
    if isinstance(item, list):
        return any(contains(v, None, values) for v in item)  

def validate(d):
    return contains(d, 'businessArea', ['Accounting']) and contains(d, 'Designation', ['L2'])
result = [d for d in test if validate(d)] 
print(result)

I got one output for above code which is correct

search_dict will dynamically come to me, so I wrote below code, but i am getting full test dictionary

search_dict  = {'businessArea': ['Research'], 'Designation': ['L2']}
return_string = " and ".join([f"contains(d, '{k}', {v})" for k, v in search_dict .items()])


def contains(item, field, values):
    if field:
        item = item.get(field)     
    if item is None:
        return None                
    if isinstance(item, str):
        return item in values       
    if isinstance(item, list):
        return any(contains(v, None, values) for v in item)  
    
def validate(d):
    return_string = " and ".join([f"contains(d, '{k}', {v})" for k, v in search_dict .items()])
    #print (return_string)
    return return_string
result = [d for d in test if validate(d)] 
print(result)

I got full dictionary which is not correct.

Any alternate method like recursion also is fine for me.

Why am i writing the second case. I don't want to manually write permutation and combination contains as like in first case

Upvotes: 4

Views: 1036

Answers (2)

a_guest
a_guest

Reputation: 36249

You can use all in order to verify that all items in the dict obey the condition:

def validate(d):
    return all(contains(d, k, v) for k, v in search_dict.items())

Upvotes: 5

Arthur
Arthur

Reputation: 1984

Are you trying to return the elements of test that contain the pairs key,value specified by search_dict?

In this case, would this work for you?:

def validate(d):
    for k,v in search_dict.items():
        if not contains(d, k, v):
            return False
    return True
result = [d for d in test if validate(d)] 
print(result)

Note that it is usually not great practice to try to write a string that will be then executed as code.

Upvotes: 3

Related Questions