I'm trying to count the number of times a specified key occurs in my list of dicts. I've used Counter()
and most_common(n)
to count up all the keys, but how can I find the count for a specific key? I have this code, which does not work currently:
def Artist_Stats(self, artist_pick):
entries = TopData(self.filename).data_to_dict()
for d in entries:
x = d['artist']
find_artist = Counter()
print find_artist[x][artist_pick]
The "entries" data has about 60k entries and looks like this:
[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]
The idea is to use list method count () to count number of occurrences. Counter method returns a dictionary with occurrences of all elements as a key-value pair, where key is the element and value is the number of times that element has occurred.
The idea is to use list method count () to count number of occurrences. Counter method returns a dictionary with occurrences of all elements as a key-value pair, where key is the element and value is the number of times that element has occurred. How to Count the NaN Occurrences in a Column in Pandas Dataframe?
Given a list in Python and a number x, count number of occurrences of x in the given list. Examples: Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10] x = 10 Output : 3 10 appears three times in given list. We keep a counter that keeps on increasing if the esquired element is found in the list.
This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased. Attention geek!
You could extract it, put it into a list, and calculate the list's length.
key_artists = [k['artist'] for k in entries if k.get('artist')]
len(key_artists)
Edit: using a generator expression might be better if your data is big:
key_artists = (1 for k in entries if k.get('artist'))
sum(key_artists)
2nd Edit:
for a specific artist, you would replace if k.get('artist')
with if k.get('artist') == artist_pick
3rd Edit: you could loop as well, if you're not comfortable with comprehensions or generators, or if you feel that enhances code readability
n = 0 # number of artists
for k in entries:
n += 1 if k.get('artist') == artist_pick else 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With