简体   繁体   中英

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

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:

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

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']})
G_list = ['BRAF\tGly464Glu', 'BRAF\tGly464Val', 
'BRAF\tGly466Glu', 'BRAF\tGly466Val']
d={ }
for s in G_list :
     u, v = s.spilt("\t")
     d.setdefault(u, [ ]).append(v)
 Print(d)

def Convert(lst):

res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}

return res_dct

    

lst = ['BRAF\\tGly464Glu', 'BRAF\\tGly464Val', 'BRAF\\tGly466Glu', 'BRAF\\tGly466Val']

print(Convert(lst))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM