简体   繁体   中英

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'] 

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM