Skip to content Skip to sidebar Skip to footer

Create Dictionary With Multiple Values Per Key

How can I create a dictionary with multiple values per key from 2 lists? For example, I have: >>> list1 = ['fruit', 'fruit', 'vegetable'] >>> list2 = ['apple', '

Solution 1:

You can use collections.defaultdict for such tasks :

>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> for i,j in zip(list1,list2):
...    d[i].append(j)
... 
>>> d
defaultdict(<type 'list'>, {'vegetable': ['carrot'], 'fruit': ['apple', 'banana']})

Solution 2:

This is a bit different from the other answers. It is a bit simpler for beginners.

list1 = ['fruit', 'fruit', 'vegetable']
list2 = ['apple', 'banana', 'carrot']
dictionary = {}

for i in list1:
    dictionary[i] = []

for i in range(0,len(list1)):
    dictionary[list1[i]].append(list2[i])

It will return

{'vegetable': ['carrot'], 'fruit': ['apple', 'banana']}

This code runs through list1 and makes each item in it a key for an empty list in dictionary. It then goes from 0-2 and appends each item in list2 to its appropriate category, so that index 0 in each match up, index 1 in each match up, and index 2 in each match up.


Post a Comment for "Create Dictionary With Multiple Values Per Key"