ttdinh
ttdinh

Reputation: 23

Python: Converting a list into a dictionary?

I have a list:

['100 ug/ml', '50 ug/ml', '25 ug/ml', '12.5 ug/ml', '6.25 ug/ml', '3.125 ug/ml', 
 '1.5625 ug/ml', '0 ug/ml']

and I want to make it into a dictionary where these numbers are keys with empty values:

growth_data = {'100 ug/ml': '', '50 ug/ml': '', '25 ug/ml': '', etc...} 

Upvotes: 2

Views: 173

Answers (2)

Gabe
Gabe

Reputation: 86708

You're looking for the dict.fromkeys() method. The first parameter is the list (or iterable) that you want to use as the keys in your dictionary; the second (optional) one is the value for each key. If you give no second argument, None will be the value of each key. Be careful with using a mutable object (like []) as your default value, as it will be the same instance shared among all the keys.

l = ['100 ug/ml', '50 ug/ml', '25 ug/ml', '12.5 ug/ml', '6.25 ug/ml',
     '3.125 ug/ml', '1.5625 ug/ml', '0 ug/ml']

growth_data = dict.fromkeys(l, '')

Upvotes: 8

BrenBarn
BrenBarn

Reputation: 251355

Assuming x is your list, do dict((a, '') for a in x).

Upvotes: 5

Related Questions