l0n3_w01f
l0n3_w01f

Reputation: 85

Value look-up for Dictionary inside a dictionary in Python

I have a Python dictionary in this format :

mongo = {
    1: {'syno': ['a','b','c'], 'can': ['2','3','4']},
    2 :{'syno': ['x','y','z'], 'can': ['6','7','8']},
}

and I have a list called syno_iter:

syno_iter = ['a','b','c','d','e']

Using a single value in syno_iter, let's suppose a. I want to get the values in the can in the mongo{} as in if the value a is available in the value of the value syno, we can return can.

We don't have any way of knowing the keys of mongo dict. Also as dictionaries are not iterable we can't use range thing.

To reiterate:

I want to do something like this-

for i in syno_iter:
    if i in (mongo.values('syno')):
        print mongo.values('can'(values()))
input - 'a'
output - ['2','3','4']

Upvotes: 0

Views: 91

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49842

You can perform a lookup like that with:

Code:

def get_syno_values(data, lookup):
    for row in data.values():
        if lookup in row['syno']:
            return row['can']

Test Code:

mongo = {
    1: {'syno': ['a', 'b', 'c'], 'can': ['2', '3', '4']},
    2: {'syno': ['x', 'y', 'z'], 'can': ['6', '7', '8']}
}
syno_iter = ['a', 'b', 'c', 'd', 'e']

print(get_syno_values(mongo, 'a'))
print(get_syno_values(mongo, 'y'))

Results:

['2', '3', '4']
['6', '7', '8']

Upvotes: 1

Related Questions