Souames
Souames

Reputation: 1145

How to find dict in a list of dict based on a value in a list?

I have a list of dicts where each dict contains a list, here's an example:

[{ "1": [0,1,2,3]},{ "2": [4,5]},{ "3": [6,7,8,9,10,11]},{ "4": [12] }]

I'm struggling to build a function that would take a value as input and return the correspending key :

print(somefunc(12)) # Should print 4
print(somefunc(5)) # should print 2

I'm sure that each value in each list is unique, so I don't have to care about the case where I would have the same value in different lists.

What's the pythonic way to do this, I have tried to do some math logic by deviding the index over the sum and checks if it's smaller than 1, but with no success.

Upvotes: 0

Views: 52

Answers (2)

Vasu Devan
Vasu Devan

Reputation: 176

[list(item.keys())[0] for item in ls if val in list(item.values())[0]]

Upvotes: 0

JacobIRR
JacobIRR

Reputation: 8966

Loop over the list, then the dict items, then check the value and return the key if you find that value:

def somefunc(val):
    l = [{ "1": [0,1,2,3]},{ "2": [4,5]},{ "3": [6,7,8,9,10,11]},{ "4": [12] }]

    for dictionary in l:
        for key, v_list in dictionary.items():
            if val in v_list:
                return key

Upvotes: 2

Related Questions