How to create a dictionary w/ key having multiple values from two lists?

Question:

I have two list:

List2 = [Orange, Onions, Cherries, Steak, Chicken, Apples, Rice, Grapes]
List1 = [Fruits, Vegetable, Fruits, Meats, Meats, Fruits, Grains] 

I want to be able to create the following dictionary where List1 is the Key:

OUTPUT:

Dict = {
         Fruits: Orange, Cherries, Apple. Grapes
         Vegetable: Onions
         Meats: Steak, Chicken
         Grains: Rice}

I tried something like:

List2 = [Orange, Onions, Cherries, Steak, Chicken, Apples, Rice, Grapes]
List1 = [Fruits, Vegetable, Fruits, Meats, Meats, Fruits, Grains] 

for e, f in zip (list1, list2):
     if e == set(e):
          for f in list2:
               d = {e:f}
Asked By: thoughtcrime

||

Answers:

Use collections.defaultdict object to accumulate values for the same keys:

from collections import defaultdict

lst2 = ['Orange', 'Onions', 'Cherries', 'Steak', 'Chicken', 'Apples', 'Rice']
lst1 = ['Fruits', 'Vegetable', 'Fruits', 'Meats', 'Meats', 'Fruits', 'Grains']

d = defaultdict(list)
for k, v in zip(lst1, lst2):
    d[k].append(v)

print(dict(d))

{'Fruits': ['Orange', 'Cherries', 'Apples'], 
 'Vegetable': ['Onions'], 
 'Meats': ['Steak', 'Chicken'],
 'Grains': ['Rice']}
Answered By: RomanPerekhrest

i think the solution:

key = set(list1)
dict={}
for x, y in zip(list1, list2):
     for k in key:
       if x == k:
         dict.setdefault(k,[])
         dict[k].append(y)
Answered By: thoughtcrime

enter image description here

Solution works fine w/out the need of additional modules @communitybot.

Answered By: thoughtcrime
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.