Convert a list to a dictionary in Python

前端 未结 12 1994
無奈伤痛
無奈伤痛 2020-11-22 04:14

Let\'s say I have a list a in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following o

相关标签:
12条回答
  • 2020-11-22 05:07

    You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:

    dict(izip(*([iter(a)]*2)))
    

    If you have a generator a, even better:

    dict(izip(*([a]*2)))
    

    Here's the rundown:

    iter(h)    #create an iterator from the array, no copies here
    []*2       #creates an array with two copies of the same iterator, the trick
    izip(*())  #consumes the two iterators creating a tuple
    dict()     #puts the tuples into key,value of the dictionary
    
    0 讨论(0)
  • 2020-11-22 05:10

    Simple answer

    Another option (courtesy of Alex Martelli - source):

    dict(x[i:i+2] for i in range(0, len(x), 2))
    

    Related note

    If you have this:

    a = ['bi','double','duo','two']
    

    and you want this (each element of the list keying a given value (2 in this case)):

    {'bi':2,'double':2,'duo':2,'two':2}
    

    you can use:

    >>> dict((k,2) for k in a)
    {'double': 2, 'bi': 2, 'two': 2, 'duo': 2}
    
    0 讨论(0)
  • 2020-11-22 05:10

    try below code:

      >>> d2 = dict([('one',1), ('two', 2), ('three', 3)])
      >>> d2
          {'three': 3, 'two': 2, 'one': 1}
    
    0 讨论(0)
  • 2020-11-22 05:13
    {x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}
    
    result : {'hello': 'world', '1': '2'}
    
    0 讨论(0)
  • 2020-11-22 05:17

    I am also very much interested to have a one-liner for this conversion, as far such a list is the default initializer for hashed in Perl.

    Exceptionally comprehensive answer is given in this thread -

    • python convert list to dictionary

    Mine one I am newbie in Python), using Python 2.7 Generator Expressions, would be:

    dict((a[i], a[i + 1]) for i in range(0, len(a) - 1, 2))

    0 讨论(0)
  • 2020-11-22 05:19
    b = dict(zip(a[::2], a[1::2]))
    

    If a is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.

    from itertools import izip
    i = iter(a)
    b = dict(izip(i, i))
    

    In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range() and len(), which would normally be a code smell.

    b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
    

    So the iter()/izip() method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip() is already lazy in Python 3 so you don't need izip().

    i = iter(a)
    b = dict(zip(i, i))
    

    If you want it on one line, you'll have to cheat and use a semicolon. ;-)

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