0

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".

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
crypatix
  • 55
  • 6
  • You know what's your input, you know what's the expected output. It's quite hard to find a task impossible to be done in Python. So the answer is: yes, it is possible. It can even be done in several ways. The question is: what have you tried? – freakish Nov 27 '14 at 06:45
  • BTW: `['RH50A, CD241, SLC42A1']`. Didn't you mean `['RH50A', 'CD241', 'SLC42A1']`? – freakish Nov 27 '14 at 06:48
  • For that one, I'm not so sure, because i literally just copy and pasted what the results were when I printed it out on python. I've tried looping through both but it doesn't seem to produce any outputs @freakish – crypatix Nov 27 '14 at 07:03

3 Answers3

1

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.

ComputerFellow
  • 11,710
  • 12
  • 50
  • 61
0

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

Community
  • 1
  • 1
0
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']