-3

I have

listOfElements = ["O", "C", "H", "H", "N", "O", "H"]

What's the best way to turn this into this dictionary-

dicOfElements = {"O":2, "C":1, "H":3, "N":1}

blackbrandt
  • 2,010
  • 1
  • 15
  • 32
jkally
  • 794
  • 2
  • 9
  • 35

1 Answers1

2

Use collections.Counter:

from collections import Counter

listOfElements = ["O", "C", "H", "H", "N", "O", "H"]
c = Counter(listOfElements)
dict(c)
# {'C': 1, 'H': 3, 'N': 1, 'O': 2}
Lante Dellarovere
  • 1,838
  • 2
  • 7
  • 10