将两个列表转换为字典,其值为列表

Abh*_*tia 1 python nlp python-2.7

我可以将两个列表转换为字典

>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print dictionary
Run Code Online (Sandbox Code Playgroud)

如何使用键将值转换为字典,但将值转换为列表.

keys = ['a', 'b', 'c' ,'a']
values=[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

输出:

{'a': [1,4], 'c': [3], 'b': [2]}
Run Code Online (Sandbox Code Playgroud)

我在依赖解析器中使用它来获取文本中名词的相应形容词.注意我必须为大文本执行此操作,因此效率很重要.

请说明接近的计算时间.

DSM*_*DSM 5

我只是遍历键/值对并使用setdefault它们将它们添加到字典中:

>>> keys = ['a', 'b', 'c' ,'a']
>>> values=[1, 2, 3, 4]
>>> d = {}
>>> for k,v in zip(keys, values):
...     d.setdefault(k, []).append(v)
...     
>>> d
{'c': [3], 'b': [2], 'a': [1, 4]}
Run Code Online (Sandbox Code Playgroud)