One liner: creating a dictionary from list with indices as keys

前端 未结 5 1802
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 15:03

I want to create a dictionary out of a given list, in just one line. The keys of the dictionary will be indices, and values will be the elements of the list. Someth

相关标签:
5条回答
  • 2020-11-27 15:31

    Simply use list comprehension.

    a = [51,27,13,56]  
    b = dict( [ (i,a[i]) for i in range(len(a)) ] )
    print b
    
    0 讨论(0)
  • 2020-11-27 15:36
    a = [51,27,13,56]
    b = dict(enumerate(a))
    print(b)
    

    will produce

    {0: 51, 1: 27, 2: 13, 3: 56}
    

    enumerate(sequence, start=0)

    Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

    0 讨论(0)
  • 2020-11-27 15:38

    With another constructor, you have

    a = [51,27,13,56]         #given list
    d={i:x for i,x in enumerate(a)}
    print(d)
    
    0 讨论(0)
  • 2020-11-27 15:39

    Try enumerate: it will return a list (or iterator) of tuples (i, a[i]), from which you can build a dict:

    a = [51,27,13,56]  
    b = dict(enumerate(a))
    print b
    
    0 讨论(0)
  • 2020-11-27 15:45
    {x:a[x] for x in range(len(a))}
    
    0 讨论(0)
提交回复
热议问题