简体   繁体   中英

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!

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'])])
>>> 

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']})

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'])])

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