Home > Mobile >  How to make dictionary using two lists which contains multiple values for one key?
How to make dictionary using two lists which contains multiple values for one key?

Time:02-08

I want to make a dictionary out of the two lists "a" and "b" in which a contains the keys and b contains values but the problem is that there are multiple values for one key

a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']

expected output should be like

{'Eng':['Noun','Pronoun','Tenses'],'Science':['Light','Sound'],'Maths':['Algebra','Probability']}

CodePudding user response:

You have an extra entry in a in your input. Removing the extra Hindi from a so that len(a) = len(b). You can use following small snippet -

d = {}
for i,j in zip(a,b):
    d.setdefault(i, []).append(j)

output d -

{'Eng': ['Noun', 'Pronoun', 'Tenses'], 'Science': ['Light', 'Sound'], 'Maths': ['Algebra', 'Probability']}

CodePudding user response:

Loop over the lists.

myDict = {}
for i,j in zip(a,b):
  if i in myDict.keys():
    myDict[i].append(j)
  else:
    myDict[i] = [j]

Result will be:

{'Eng': ['Noun', 'Pronoun', 'Tenses'], 'Science': ['Light', 'Sound'], 'Hindi': ['Algebra'], 'Maths': ['Probability']}
  •  Tags:  
  • Related