Home > Mobile >  Is there a way of only printing the dictionary in a Counter() output?
Is there a way of only printing the dictionary in a Counter() output?

Time:09-27

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?

CodePudding user response:

print(dict(colorTotals))

Which outputs

{'green': 2, 'blue': 1, 'white': 2}

CodePudding user response:

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.

CodePudding user response:

You will need to convert colorTotals to a string and then slice it:

colorTotals = str(Counter(colors))[8:-1]

If you want to extract the dictionary out of the Counter list and keep it a dictionary, you will need to use ast.literal_eval:

import ast

colorTotals = str(Counter(colors))[8:-1]
dictColorTotals = ast.literal_eval(colorTotals)

print(dictColorTotals)
  • Related