简体   繁体   中英

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:

>>> 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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