Home > Back-end >  How to create a dictionary w/ key having multiple values from two lists?
How to create a dictionary w/ key having multiple values from two lists?

Time:12-26

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}

CodePudding user response:

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

CodePudding user response:

thank you for sharing your knowlodge

CodePudding user response:

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)
  • Related