Convert python list to dictionary

前端 未结 3 1186
梦如初夏
梦如初夏 2021-01-26 02:19

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

3条回答
  •  失恋的感觉
    2021-01-26 02:40

    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

提交回复
热议问题