Matty
Matty

Reputation: 458

Search Lists in dict for Value, if found return dict identifier

Hard to explain so I will put an example below:

res = {
  "merchantPermissionsMap" : {
    "33427" : ["AAA", "BBB", "CCC"],
    "12345": ["AAA", "CCC"],
    "67890": ["BBB"]
  }
}

So I need to search res['merchantPermissionsMap'] for any occurrence of a permission, and if found return the corresponding id.

I know the below is wrong, but this is how I expect it to flow:

message = ''
for i in res['merchantPermissionsMap']:
    if 'BBB' in i:
        message += f" {i}"
print(f"BBB appears in{message}")

Output would be: BBB appears in 33427, 67890

Upvotes: 0

Views: 50

Answers (3)

Juhi Dhameliya
Juhi Dhameliya

Reputation: 169

you need to iterate through your dictionary to get desired output. Try below code ;

def search(res,string):
a=[]
for key, value in res.items():
    for k,v in value.items():
        if 'BBB' in v:
            a.append(k)
return a

print(search(res.'BBB'))

Upvotes: 0

deadshot
deadshot

Reputation: 9061

You are checking the BBB in key you should check value here i is a key

for i in res['merchantPermissionsMap']:
    print(i)

Output:

33427
12345
67890

You should change your if condition if 'BBB' in res['merchantPermissionsMap'][i]

for i in res['merchantPermissionsMap']:
    if 'BBB' in res['merchantPermissionsMap'][i]:
        message += f" {i}"
print(f"BBB appears in{message}")

Upvotes: 2

bigbounty
bigbounty

Reputation: 17368

You can use list comprehension to get the desired result


res = {
  "merchantPermissionsMap" : {
    "33427" : ["AAA", "BBB", "CCC"],
    "12345": ["AAA", "CCC"],
    "67890": ["BBB"]
  }
}

appears = ", ".join([k for k,v in res["merchantPermissionsMap"].items() if "BBB" in v])

print(f"BBB appears in {appears}")

Output:

BBB appears in 33427, 67890

OR

your code, you are looping through the keys of the merchantPermissionsMap dict. Or loop through key and value via .items()

for k,v in res['merchantPermissionsMap'].items():
    if 'BBB' in v:
        message += f" {k}"
print(f"BBB appears in{message}")

Upvotes: 0

Related Questions