简体   繁体   English

将两个列表转换为带有值作为列表的字典

[英]Convert two lists to dictionary with values as list

I can convert two lists to dictionary 我可以将两个列表转换成字典

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

How to convert it to dictionary with keys but values as list. 如何使用键但值作为列表将其转换为字典。

keys = ['a', 'b', 'c' ,'a']
values=[1, 2, 3, 4]

Output: 输出:

{'a': [1,4], 'c': [3], 'b': [2]}

I am using this in dependency parser to get corresponding adjectives for nouns in text. 我在依赖解析器中使用它来获取文本中名词的对应形容词。 Note I have to do this for huge text so efficency matters. 注意我必须对大量文本执行此操作,因此效率很重要。

Please state the computational time of approach as well. 请同时说明进近的计算时间。

I'd simply loop over the key/value pairs and use setdefault to add them to the dictionary: 我只是简单地遍历键/值对,然后使用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]}

Presuming both lists have the same length: 假设两个列表的长度相同:

>>> import collections
>>> keys = ['a', 'b', 'c' ,'a']
>>> values = [1, 2, 3, 4]
>>> r = collections.defaultdict(list)

>>> for i, key in enumerate(keys):
...     r[key].append(values[i])

The function itertools.groupby takes a list and groups neighboring same elements together. itertools.groupby函数获取一个列表并将相邻的相同元素分组在一起。 We need to sort the zipped list to ensure that equal keys end up next to each other. 我们需要对压缩列表进行排序,以确保相等的键最终彼此相邻。

import itertools
keys = ['a', 'b', 'c', 'a']
values = [1, 2, 3, 4]
data = sorted(zip(keys, values))
dictionary = {}
for k, g in itertools.groupby(data, key=lambda x: x[0]):
    dictionary[k] = [x[1] for x in g]
print(dictionary)
# {'c': [3], 'b': [2], 'a': [1, 4]}

There's probably a better way to do this. 可能有更好的方法可以做到这一点。 But here's one solution: 但这是一种解决方案:

keys = ['a', 'b', 'c' ,'a']
values=[1, 2, 3, 4]

combined = {}

for k, v in zip(keys, values):
    l = combined.get(k, [])
    l.append(v)
    combined[k] = l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM