Reputation: 139
How can I create a dictionary with multiple values per key from 2 lists?
For example, I have:
>>> list1 = ['fruit', 'fruit', 'vegetable']
>>> list2 = ['apple', 'banana', 'carrot']
And, I want something to the effect of:
>>> dictionary = {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
I have tried the following so far:
>>> keys = list1
>>> values = list2
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'fruit': 'banana', 'vegetable': 'carrot'}
Upvotes: 4
Views: 7820
Reputation: 3651
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.
Upvotes: 5
Reputation: 107347
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']})
Upvotes: 6
Reputation:
You can use dict.setdefault
and a simple for-loop:
>>> list1 = ["fruit", "fruit", "vegetable"]
>>> list2 = ["apple", "banana", "carrot"]
>>> dct = {}
>>> for i, j in zip(list1, list2):
... dct.setdefault(i, []).append(j)
...
>>> dct
{'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
From the docs:
setdefault(key[, default])
If
key
is in the dictionary, return its value. If not, insertkey
with a value ofdefault
and returndefault
.default
defaults toNone
.
Upvotes: 9