-1

I am counting the total occurrences of each item:

from collections import Counter

colors = ['green', 'blue', 'green', 'white', 'white']
colorTotals = Counter(colours)

print(colorTotals)

Running the code prints: Counter({'green': 2, 'white': 2, 'blue': 1}) but I only want to print the dictionary, something like: {'green': 2, 'white': 2, 'blue': 1}

How can I achieve this?

2 Answers2

2
print(dict(colorTotals))

Which outputs

{'green': 2, 'blue': 1, 'white': 2}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

dict(colorTotals) is the standard way. If you're golfing, you could also use {**colorTotals} or {}|colorTotals or colorTotals|{} (the latter two require Python 3.9). I see no circumstance where you'd ever use your str+literal_eval way.

no comment
  • 6,381
  • 4
  • 12
  • 30