1

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.

Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142

4 Answers4

5

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]}
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    I might add a link to the function https://docs.python.org/2/library/stdtypes.html#dict.setdefault - so that future browsers can have a look what it does... – J Richard Snape Sep 08 '15 at 08:49
2

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])
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
1

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]}
Mathias Rav
  • 2,808
  • 14
  • 24
0

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