Filipe
Filipe

Reputation: 13

Saving a variable and a constant in a dictionary on Python

so I am making a code on Python, but I don't know much about the language so I am having some problems. What I would like to do is that: For example I have a list of musical genres (rock, pop, hip hop) and a list of classifications (bad, good, normal), and I have a dictionary (genredict), what I would like to do is when I am running my code, each time that it reachs a genre, I would get its classification and increment one. like for example:

    genredict['rock'] = 'good', ++1 'something like this, for sure this part won't work'

I thought about creating a dictionary for each genre, but there are A LOT of genres on my list, so it would not be the best way to solve the problem. So anyone knows how can I save one key and multiple values on a dictionary where one of the values can be incremented while the other one is constant?

Thanks for the help guys.

Upvotes: 1

Views: 119

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121944

I would use nested dictionaries, and the easiest way to implement this would be using a defaultdict of Counter:

>>> from collections import Counter, defaultdict
>>> genredict = defaultdict(Counter)
>>> genredict
defaultdict(<class 'collections.Counter'>, {})  # starts off empty
>>> genredict['rock']['good'] += 1  # increment appropriate genre/rating
>>> genredict['blues']['normal'] += 1
>>> genredict
defaultdict(<class 'collections.Counter'>, 
            {'blues': Counter({'normal': 1}), 'rock': Counter({'good': 1})})
>>> genredict['rock']['good']  # retrieve current score
1

Upvotes: 1

Related Questions