I have basically a list of all the files in a folder, which in a simplified version looks like :
file_list = [ 'drug.resp1.17A.tag', 'drug.resp1.96A.tag', 'drug.resp1.56B.tag', 'drug.resp2.17A.tag', 'drug.resp2.56B.tag', 'drug.resp2.96A.tag']
Another list :
drug_list = [ '17A', '96A', '56B']
I want to combine these two list into a dictionary, such that:
dictionary = {
'17A' : ['drug.resp1.17A.tag' , 'drug.resp2.17A.tag' ],
'96A' : ['drug.resp1.96A.tag' , 'drug.resp2.96A.tag' ],
'56B' : ['drug.resp1.56B.tag' , 'drug.resp2.56B.tag' ]}
I thought of doing like this but got stuck !
dict_drugs = {}
for file in file_list:
list_filename = file.split('.')
for elem in drug_list:
if elem in list_filename:
What can I do after this to join the elements into a dictionary, or am I doing this completely wrong ?
The basic method that can be applied to perform this task is the brute force method to achieve this. For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs to from list values to dictionary.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
well you don't need inner loop
>>> file_list = [ 'drug.resp1.17A.tag', 'drug.resp1.96A.tag', 'drug.resp1.56B.tag', 'drug.resp2.17A.tag', 'drug.resp2.56B.tag', 'drug.resp2.96A.tag']
>>> dictonary = {}
... for i in file_list:
... k = i.split('.')[-2]
... if k in dictonary:
... dictonary[k].append(i)
... else:
... dictonary[k] = [i]
>>> dictonary
62: {'17A': ['drug.resp1.17A.tag', 'drug.resp2.17A.tag'],
'56B': ['drug.resp1.56B.tag', 'drug.resp2.56B.tag'],
'96A': ['drug.resp1.96A.tag', 'drug.resp2.96A.tag']}
>>>
one more check if only needs those values that are present in drug_list
means if file_list contains :
file_list = [ 'drug.resp1.18A.tag', 'drug.resp1.96A.tag', 'drug.resp1.56B.tag', 'drug.resp2.17A.tag', 'drug.resp2.56B.tag', 'drug.resp2.96A.tag']
>>> drug_list = [ '17A', '96A', '56B']
... dictonary = {}
... for i in file_list:
... k = i.split('.')[-2]
... if k in drug_list:
... if k in dictonary:
... dictonary[k].append(i)
... else:
... dictonary[k] = [i]
>>>
One more way to efficently do upper case:
dictonary = dict(((i,[]) for i in drug_list))
dictonary = {drug: [] for drug in drug_list} # As @J.F. Sebastian suggested.
for file in file_list:
k = file.split('.')[-2]
if k in dictonary:
dictonary[k].append(file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With