Convert python list to dictionary

前端 未结 3 1184
梦如初夏
梦如初夏 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:30

    you should do this instead.

    li = ['a', 'b', 'c', 'd']
    
    my_d = {letter:[] for letter in li}
    
    0 讨论(0)
  • 2021-01-26 02:36

    Use a dict comprehension:

    d = {key: [] for key in l}
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题