michael0196
michael0196

Reputation: 1637

How do I convert a list with values of different lengths into a dictionary?

For example, how do I get from:

list1 = ['ko', 'aapl', 'hon', 'disca']

to:

dict1 = {'ko': {}, 'aapl': {}, 'hon': {}, 'disca': {}}

The method I've been able to find

dict(list1)

unfortunately does not work here and returns the following error:

ValueError: dictionary update sequence element #1 has length 4; 2 is required

Thank you for your help!

Upvotes: 1

Views: 77

Answers (2)

Dawit Abate
Dawit Abate

Reputation: 460

dict(zip(list1,[{} for i in range(len(list1))]))

Upvotes: 0

sacuL
sacuL

Reputation: 51395

Try the following dictionary iteration:

dict1 = {i:{} for i in list1}

if you don't like the dictionary interation syntax, here it is in a plain loop:

dict1={}
for i in list1:
    dict1[i] = {}

Upvotes: 3

Related Questions