foosion
foosion

Reputation: 7908

Find dict by two values

able is a list of tuples and beta is a list of dicts. able and beta have the same number of elements. Order is not guaranteed.

Given an able, find the dict in beta where the value of beta[10] equals able[0] and value of beta[20] equals able[1].

There will always be a unique match.

The following works, but there has to be a better way. I just can't figure out what it is.

able = [(1,2), (3,4), (1,4), (3,5)]
beta = [{10:1, 20:2, 30:3}, {10:3, 20:4, 30:55}, {10:3, 20:5, 30:66}, {10:1, 20:4, 30:11}]

for a in able:
    for b in beta:
        if a[0] == b[10] and a[1] == b[20]:
            print(b)
            break

I suppose I could sort both able and beta. Then the Nth able would correspond to the Nth beta, so determine the index of the given able and report the beta with that index. This doesn't seem much better or more pythonic.

Upvotes: 2

Views: 27

Answers (1)

Yam Mesicka
Yam Mesicka

Reputation: 6601

Generate a dictionary with keys that correspond to the values you want to find:

beta2 = {(b[10], b[20]): b for b in beta}
print([beta2[a] for a in able])

Upvotes: 2

Related Questions