简体   繁体   中英

Handeling Dictionary of lists using Python

I have a single dictionary that contains four keys each key representing a file name and the values is nested lists as can be seen below:

{'file1': [[['1', '909238', '.', 'G', 'C', '131', '.', 'DP=11;VDB=3.108943e02;RPB=3.171491e-01;AF1=0.5;AC1=1;DP4=4,1,3,3;MQ=50;FQ=104;PV4=0.55,0.29,1,0.17', 'GT:PL:GQ', '0/1:161,0,131:99'], ['1', '909309', '.', 'T', 'C', '79', '.', 'DP=9;VDB=8.191851e-02;RPB=4.748531e-01;AF1=0.5;AC1=1;DP4=5,0,1,3;MQ=50;FQ=81.7;PV4=0.048,0.12,1,1', 'GT:PL:GQ', '0/1:109,0,120:99']......,'008_NTtrfiltered': [[['1', '949608', '.', 'G', 'A',...}

My question is how to check only the first two elements in the list for instance "1", "909238" for each of the key if they are the same and then write them to a file. The reason I want to do this is I want to filter only common values (only the first two elements of the list) for the four files (keys).

Thanks a lot in advance Best.

You can access to the keys of the dictionary dictio and make your comparison using :

f = open('file.txt','w')
value_to_check_1 = '1'
value_to_check_2 = '909238'

for k in dictio:
   value_1 = dictio[k][0][0][0]
   value_2 = dictio[k][0][0][1]
   if (( value_1 == value_to_check_1) and (value_2 == value_to_check_2)):
          f.write('What you want to write\n')
f.close()

If you want to do a check that imply every values of your dictionary dictio.

Maybe you want to store couples of values from dictio .

couples = [(dictio[k][0][0][0], dictio[k][0][0][1]) for k in dictio]

Then, you can do a loop and iterate over the couples to do your check.

Example you can adapt according to your need :

for e in values_to_check:
     for c in couples:
           if (float(e[0][0][0]) >= float(c[0]) and float(e[0][0][1]) <= float(c[1])):
                     f.write(str(e[0][0][0]) + str(e[0][0][1])  + '\n') 

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