Convert a list to a dictionary in Python

前端 未结 12 1993
無奈伤痛
無奈伤痛 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 04:53

    You can also try this approach save the keys and values in different list and then use dict method

    data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']
    
    keys=[]
    values=[]
    for i,j in enumerate(data):
        if i%2==0:
            keys.append(j)
        else:
            values.append(j)
    
    print(dict(zip(keys,values)))
    

    output:

    {'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}
    
    0 讨论(0)
  • 2020-11-22 05:01

    May not be the most pythonic, but

    >>> b = {}
    >>> for i in range(0, len(a), 2):
            b[a[i]] = a[i+1]
    
    0 讨论(0)
  • 2020-11-22 05:03

    You can also do it like this (string to list conversion here, then conversion to a dictionary)

        string_list = """
        Hello World
        Goodbye Night
        Great Day
        Final Sunset
        """.split()
    
        string_list = dict(zip(string_list[::2],string_list[1::2]))
    
        print string_list
    
    0 讨论(0)
  • 2020-11-22 05:06

    You can use a dict comprehension for this pretty easily:

    a = ['hello','world','1','2']
    
    my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}
    

    This is equivalent to the for loop below:

    my_dict = {}
    for index, item in enumerate(a):
        if index % 2 == 0:
            my_dict[item] = a[index+1]
    
    0 讨论(0)
  • 2020-11-22 05:06

    I am not sure if this is pythonic, but seems to work

    def alternate_list(a):
       return a[::2], a[1::2]
    
    key_list,value_list = alternate_list(a)
    b = dict(zip(key_list,value_list))
    
    0 讨论(0)
  • 2020-11-22 05:07

    Something i find pretty cool, which is that if your list is only 2 items long:

    ls = ['a', 'b']
    dict([ls])
    >>> {'a':'b'}
    

    Remember, dict accepts any iterable containing an iterable where each item in the iterable must itself be an iterable with exactly two objects.

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