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