pyboy
pyboy

Reputation: 47

Form a dictionary that key is from a list, value is the occurrence of items in another list in Python

Given two lists with the same length:

List1 = ['a','b','c','d','b','a','b','c']
List2 = ['1','2','3','4','5','6','7','8']

I want output the a dict as:

dic = {'a':['1','6'], 'b':['2','5','7'], 'c':['3','8'], 'd':['4']}

How to implement it in Python? Thanks!

Upvotes: 3

Views: 47

Answers (3)

Abhijit
Abhijit

Reputation: 63727

An alternate solution using itertools.groupby. In-fact, groupby seems more natural solution as it is more explicit in what it tends to achieve. To summarize, combine both the lists and group them based on the first item in the list.

Implementation

>>> from itertools import groupby
>>> from operator import itemgetter
>>> {k: map(itemgetter(1), v)
     for k, v in groupby(sorted(zip(List1, List2)),
                         key = itemgetter(0))}

Output

{'a': ['1', '6'], 'c': ['3', '8'], 'b': ['2', '5', '7'], 'd': ['4']}

Off-course as others have mentioned, if the order is important, you can use collections.OrderedDict

Implementation

>>> from collections import OrderedDict
>>> OrderedDict((k, map(itemgetter(1), v))
                for k, v in groupby(sorted(zip(List1, List2)),
                                    key = itemgetter(0)))

Output

OrderedDict([('a', ['1', '6']), ('b', ['2', '5', '7']), ('c', ['3', '8']), ('d', ['4'])])

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You can use zip function to create a list of (in python 3.X an iterator) columns and use dict.setdefault method (or collections.defaultdict) to create a desire dictionary :

>>> List1 = ['a','b','c','d','b','a','b','c']
>>> List2 = ['1','2','3','4','5','6','7','8']
>>> 
>>> d={}
>>> for i,j in zip(List1,List2):
...   d.setdefault(i,[]).append(j)
... 
>>> d
{'a': ['1', '6'], 'c': ['3', '8'], 'b': ['2', '5', '7'], 'd': ['4']}

And if you care about the order you can use collections.OrderedDict :

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j in zip(List1,List2):
...   d.setdefault(i,[]).append(j)
... 
>>> d
OrderedDict([('a', ['1', '6']), ('b', ['2', '5', '7']), ('c', ['3', '8']), ('d', ['4'])])
>>> 

Upvotes: 4

Anand S Kumar
Anand S Kumar

Reputation: 90889

I would use a collections.defaultdict and zip() method. Example -

>>> List1 = ['a','b','c','d','b','a','b','c']
>>> List2 = ['1','2','3','4','5','6','7','8']
>>>
>>> from collections import defaultdict
>>> outd = defaultdict(list)
>>> for x,y in zip(List1,List2):
...     outd[x].append(y)
...
>>> outd
defaultdict(<class 'list'>, {'c': ['3', '8'], 'd': ['4'], 'b': ['2', '5', '7'], 'a': ['1', '6']})

Upvotes: 1

Related Questions