-2
list1 = [123, 123, 123, 456]
list2 = ['word1', 'word2', 'word3', 'word4']

I want the output to be a python dictionary,

d = {123 : ['word1', 'word2', 'word3'], 456 : 'word4'}

I have multiple occurrences of values in list one, I want to map all the values of list2 to list1 without key repetition.

bharatk
  • 4,202
  • 5
  • 16
  • 30
  • 2
    Do single values such as `'word4'` have to appear as a string? Or is a list good? – yatu Oct 28 '19 at 09:27

2 Answers2

2

Here's an itertools based approach:

from itertools import groupby, islice

list1 = [123, 123, 123, 456]
list2 = iter(['word1', 'word2', 'word3', 'word4'])

{k:list(islice(list2, len(list(v)))) for k,v in groupby(list1)}
# {123: ['word1', 'word2', 'word3'], 456: ['word4']}
yatu
  • 86,083
  • 12
  • 84
  • 139
  • 2
    `'word4'` isn't in a list – Sayse Oct 28 '19 at 09:25
  • I know it's not OP's requirements, but having `word4` in a list is neat because then you don't need to differentiate between values and 1-value lists in the following code. – Guimoute Oct 28 '19 at 09:27
  • 1
    no wait it didnt work, values are repeating themselves – Akanksha Sukhramani Oct 28 '19 at 09:28
  • 1
    I think having more uniformity in the dictionary values should be more useful and also simplifies the dict generation @sayse – yatu Oct 28 '19 at 09:29
  • @yatu - I don't disagree but it doesn't (didn't) match the output of the op's request for free labour – Sayse Oct 28 '19 at 09:30
  • If you want the right output (no list for `word4`) you can use a simple dict comprehension: `{k: (v[0] if len(v) == 1 else v) for k, v in res.items()}` – Silveris Oct 28 '19 at 09:32
  • 1
    Well I think a reasonable alternative to a not yet generated output (for which perhaps better approaches exist) should be fine. Not matching 100% OPs question should not be an impediment to suggest better outputs @sayse – yatu Oct 28 '19 at 09:32
1

You can use collections and zip() method.

import collections

list1 = [123, 123, 123, 456]
list2 = ['word1', 'word2', 'word3', 'word4']

dict_value = collections.defaultdict(list)
for key, value in zip(list1, list2):
    dict_value[key].append(value)

for i in dict_value:
    print('key', i, 'items', dict_value[i], sep = '\t')

output:

key 123 items   ['word1', 'word2', 'word3']
key 456 items   ['word4']
Andrea Grioni
  • 187
  • 1
  • 9