i wonder to convert 'list to dictionary'.
input :
G_list = ['BRAF\tGly464Glu', 'BRAF\tGly464Val', 'BRAF\tGly466Glu', 'BRAF\tGly466Val']
wondering output:
{'BRAF' : ['Gly464Glu', 'Gly464Val', 'Gly466Glu', 'Gly466Val']}
Any help would be appreciated. Thanks
You can do the following:
d = {}
for s in G_list:
k, v = s.split("\t")
# k, v = s.split("\t", 1) # if the value might contain more tabs
d.setdefault(k, []).append(v)
Since this is essentially csv data (maybe coming from a file, a .csv
or rather a .tsv
), you can also consider using the csv
module. The reader
in particular will work on any iterable of strings:
from csv import reader
d = {}
for k, v in reader(G_list, delimiter="\t"):
d.setdefault(k, []).append(v)
Some docs:
str.split
dict.setdefault
csv.reader
Split by a whitespace (using str.split
) and store the results using collections.defaultdict
:
from collections import defaultdict
G_list = ['BRAF\tGly464Glu', 'BRAF\tGly464Val', 'BRAF\tGly466Glu', 'BRAF\tGly466Val']
d = defaultdict(list)
for key, value in map(str.split, G_list):
d[key].append(value)
print(d)
Output
defaultdict(<class 'list'>, {'BRAF': ['Gly464Glu', 'Gly464Val', 'Gly466Glu', 'Gly466Val']})
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