简体   繁体   中英

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!

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] = {}
dict(zip(list1,[{} for i in range(len(list1))]))

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