如何将包含重复值的列表转换为以列表作为值的字典?

Jon*_*gro 3 python list-comprehension

假设我有两个由另一个函数生成的列表:

test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
test2 = [[1, 4], [4, 1]]
Run Code Online (Sandbox Code Playgroud)

我想将它们转换为关联数组,以便快速查找,如下所示:

test: {0: [1, 2], 1: [5,6], 2: [0], 3: [99, 98, 97]}
test2: {1: [4], 4: [1]}
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

def list_to_dict(my_list):
    last_val = my_list[0][0]
    temp = []
    my_dict = {}

    for i in my_list:
        if last_val == i[0]:
            temp.append(i[1])
        else:
            #add the values to this key
            my_dict[last_val] = temp
            #reset the list
            temp = []
            temp.append(i[1])

        last_val = i[0]
    my_dict[last_val] = temp
    return my_dict
Run Code Online (Sandbox Code Playgroud)

但是,这不是非常Pythonic.是否有更多的Pythonic方法来实现这一目标?

Kas*_*mvd 5

用途collections.defaultdict:

>>> test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
>>> 
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> 
>>> for i, j in test:
...     d[i].append(j)
... 
>>> d
defaultdict(<type 'list'>, {0: [1, 2], 1: [5, 6], 2: [0], 3: [99, 89, 79]})
Run Code Online (Sandbox Code Playgroud)