-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
  • 1,768
  • 14
  • 29
jkally
  • 798
  • 2
  • 8
  • 32

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,808
  • 2
  • 6
  • 10