Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert lists to dictionary in python?

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

like image 411
union Avatar asked Mar 01 '23 10:03

union


2 Answers

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
like image 159
user2390182 Avatar answered Mar 11 '23 22:03

user2390182


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']})
like image 24
Dani Mesejo Avatar answered Mar 11 '23 22:03

Dani Mesejo