Home > Enterprise >  how to convert lists to dictionary in python?
how to convert lists to dictionary in python?

Time:10-21

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

CodePudding user response:

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:

CodePudding user response:

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']})

CodePudding user response:

One of the approaches:

from collections import defaultdict
G_list = ['BRAF\tGly464Glu', 'BRAF\tGly464Val', 'BRAF\tGly466Glu', 'BRAF\tGly466Val']
out = defaultdict(list)
for item in G_list:
    data = item.split('\t')
    out[data[0]].append(data[1])
    
print (out)

Output:

defaultdict(<class 'list'>, {'BRAF': ['Gly464Glu', 'Gly464Val', 'Gly466Glu', 'Gly466Val']})
  • Related