Following on your last post, your initial file test.txt
looks like that:
WP_XXXXXXXX2.1 PF06325 Ribosomal protein L11 methyltransferase (PrmA) 5
WP_192XXXXXX.1 PF13489 Methyltransferase domain 4
XXXXXXX45.1 PF02310 B12 binding domain 12
XXXXXXX45.1 PF04055 Radical SAM superfamily 5
WP_XXXXXXX29.1 PF13489 Methyltransferase domain 4
WP_0XXXXXXXX.1 PF13489 Methyltransferase domain 4
WP_XXXXXXX90.1 PF06325 Ribosomal protein L11 methyltransferase (PrmA) 5
WP_XXXXXXX90.1 PF06325 Ribosomal protein L11 methyltransferase (PrmA) 7
WP_0XXXXXX62.1 PF13489 Methyltransferase domain 4
And you have another file order.txt
that contains your ordered IDs:
XXXXXXX45.1
YP_343434.1
WP_XXXXXXXX2.1
WP_XXXXXXX90.1
WP_0XXXXXX62.1
XP_222222222.2
WP_192XXXXXX.1
WP_XXXXXXX29.1
WP_0XXXXXXXX.1
Since you want to merge by the first field in test.txt
and sort them according to order.txt
, you have to read first both of the files:
# read 'test.txt'
with open("test.txt",'r') as rf:
l = rf.readlines()
# read sorted IDs 'order.txt'
with open("order.txt",'r') as rf:
l_order = rf.readlines()
# remove newlines from each element in list
l_order = [i.strip() for i in l_order]
My previous answers describe how we obtain the merged fields in the file, so I will not go over it again. Since we need to sort the dictionary according to the list, we simply have to do:
# for each element in ordered list
for i in l_order:
if i in dict_id.keys(): # if element is in my dictionary's keys
print(i + "\t" + "; ".join(dict_id[i])) # print the key and the value
else:
print(I) # else prints the element
This should print:
XXXXXXX45.1 PF02310 B12 binding domain 12; PF04055 Radical SAM superfamily 5
YP_343434.1
WP_XXXXXXXX2.1 PF06325 Ribosomal protein L11 methyltransferase (PrmA) 5
WP_XXXXXXX90.1 PF06325 Ribosomal protein L11 methyltransferase (PrmA) 5; PF06325 Ribosomal protein L11 methyltransferase (PrmA) 7
WP_0XXXXXX62.1 PF13489 Methyltransferase domain 4
XP_222222222.2
WP_192XXXXXX.1 PF13489 Methyltransferase domain 4
WP_XXXXXXX29.1 PF13489 Methyltransferase domain 4
WP_0XXXXXXXX.1 PF13489 Methyltransferase domain 4
Full code:
with open("test.txt",'r') as rf:
l = rf.readlines()
with open("order.txt",'r') as rf:
l_order = rf.readlines()
l_order = [i.strip() for i in l_order]
dict_id = {}
for i in l:
key_id = i.split("\t")[0]
if key_id not in dict_id.keys():
value = "\t".join(i.split("\t")[1:]).rstrip()
dict_id[key_id] = [value]
else:
dict_id[key_id].append("\t".join(i.split("\t")[1:]).rstrip())
for i in l_order:
if i in dict_id.keys():
print(i + "\t" + "; ".join(dict_id[i]))
else:
print(i)
PS: please for further pure programming questions, do post your questions in StackOverflow instead of Bioinformatics.