简体   繁体   中英

Looping a list through dictionary values python

I was wondering if it's possible to loop a list of values
Example:

lst = ['RH', 'CD241', 'C2', 'SCZD9', 'RG59L', 'WNT3A']

through the values of a dictionary
Example:

ref_dict = {
    '': [''], '6005': ['RH50A', 'CD241', 'SLC42A1'], '603': [''],
    '6000': [''], '8787': ['PERRS', 'RGS9L', 'MGC26458'],
    '41': ['ACCN2', 'BNaC2', 'hBNaC2'], '8490': [''],
    '9628': [''], '5999': ['SCZD9']
}

To check if the individual value in the list has the value in the dictionary, if it does have the value, then it would return me the key in which the value is in.

Example : lst value CD241 is in the dictionary '6005': ['RH50A, CD241, SLC42A1'] , it would return me key "6005" .

Something like,

for key in ref_dict.keys():
    if set(lst) & set(ref_dict[key]):
        #do something with your key
        #key is the key you want

If there are multiple keys where one of the elements in lst will exist, then you can get the list of these keys with a list comprehension,

[key for key in ref_dict.keys() if set(lst) & set(ref_dict[key])]

which outputs ['6005', '5999'] for your case.

The magic is happening in the set intersection part,

(set(['RH', 'CD241', 'C2', 'SCZD9', 'RG59L', 'WNT3A']) & 
 set(['RH50A', 'CD241', 'SLC42A1']))

will give you - ['CD241'] , as good as checking if something in lst exists in the value list or not.

Try this:

for key in ref_dict:
    if ref_dict[key] != 0:
        return key
        #if you want to use the value 

This might link help

from collections import defaultdict

lst = ['RH', 'CD241', 'C2', 'SCZD9', 'RG59L', 'WNT3A']
ref_dict = {
    '': [''], '6005': ['RH50A, CD241, SLC42A1'], '603': [''],
    '6000': [''], '8787': ['PERRS, RGS9L, MGC26458'],
    '41': ['ACCN2, BNaC2, hBNaC2'], '8490': [''],
    '9628': [''], '5999': ['SCZD9']
}


all_values = defaultdict(list)
for key in ref_dict:
    for value in (map(lambda x: x.strip(), ref_dict[key][0].split(","))):
        all_values[value].append(key)

print all_values['CD241'] # ['6005']

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