python - Using list comprehension to match values of dictionaries which are stored in lists -
i have 2 lists of dictionaries need compare:
search_list =[{'chr':'chr1','st':'2345','end':'2456'}, {'chr':'chr1','st':'3457','end':'4567'}] and
database = [{'chr':'chr1','st':'2348','end':'2348'}, {'chr':'chr1','st':'190','end':'190'}] therefore each dictionary within list looks this:
{'chr':'chr1','st':'2345','end':'2456'} where chr = chromosome, st = start coordinate, , end = end coordinate.
i need identify values in database match on chr value , between st , end values (which need integers, rather current string form). can tell list comprehension best way accomplish this. looking @ this question has been conceptual starting point, i'm bit confused how proceed.
my pseudocode is:
matched = [var var in search_list search_list['chr'] == database['chr'] , search_list['st'] >= database['st'] <= search_list['end']] but that's rough! suggestions welcome.
update i've tried kobik's suggestion looks should work. having problem transforming values attached 'st' , 'end' keys strings integers in order mathematical searching.
here's i've got:
matchedvars ={[record record in database lookup in search_list if record['chr'] == lookup['chr'] if int(lookup['st']) <= int(record['st']) <= int(lookup['end'])]} but throws error:
file "snp_freq_v1-4.py", line 86, in
matchedvars ={[record record in database lookup in search_list if record['chr'] == lookup['chr'] if int(lookup['st']) <= int(record['st']) <= int(lookup['end'])]}
typeerror: string indices must integers
is there better/more appropriate way transform keys strings ints?
you can utilize list comprehension: code iterate elemnts in database dict , check criteria in search_list
search_list =[{'chr':'chr1','st':'2345','end':'2456'},{'chr':'chr2','st':'3457','end':'4567'}] database = [{'chr':'chr1','st':'2348','end':'2348'},{'chr':'chr2','st':'190','end':'190'}] print [record record in database lookup in search_list if record['chr'] == lookup['chr'] if lookup['st'] <= record['st'] <= lookup['end']] output:
[{'chr': 'chr1', 'end': '2348', 'st': '2348'}] as can see in output {'chr': 'chr1', 'end': '2348', 'st': '2348'} matching criteria's within search_list
python list dictionary list-comprehension
No comments:
Post a Comment