user1928543
user1928543

Reputation: 45

Convert python list to dictionary

I'm trying convert my list to dictionary in python. I have list l

l = ['a', 'b', 'c', 'd']

and I want convert it to dictionary d

d['a'] = []
d['b'] = []
d['c'] = []
d['d'] = []

I was trying

for i in range(0, len(l)):
    d[i][0]=l(i)

but that don't work. Thanks

Upvotes: 0

Views: 423

Answers (3)

idjaw
idjaw

Reputation: 26600

Keep it a bit simpler than that, you want to loop over your list, and then assign your iterator i (which will be each value in your list) as the key to each dictionary entry.

l = ['a', 'b', 'c', 'd']

d = {}
for i in l:
    d[i] = []


print(d) # {'a': [], 'c': [], 'b': [], 'd': []}

With the above understood, you can now actually simplify this in to one line as:

{k: [] for k in l}

The above is called a dictionary comprehension. You can read about it here

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Use a dict comprehension:

d = {key: [] for key in l}

Upvotes: 1

Seekheart
Seekheart

Reputation: 1173

you should do this instead.

li = ['a', 'b', 'c', 'd']

my_d = {letter:[] for letter in li}

Upvotes: 2

Related Questions