-1

I have a list like this:

["comp1", "comp2", "comp1", "mycomp", "mycomp"]

and I want to convert it to a dictionary like this: {“comp1” : 2, “comp2” : 1, “mycomp” : 2}

how do I do that?

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321

1 Answers1

1

This is probably the easiest way to do it:

lst =  ["comp1", "comp2", "comp1", "mycomp", "mycomp"]
d = {}
for i in lst:
    d[i] = d.get(i, 0) +1
print (d)

Output:

{'comp2': 1, 'comp1': 2, 'mycomp': 2}
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48