Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count occurrences of specific dict key in list of dicts

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'},]
like image 780
mo_shun Avatar asked Dec 12 '14 01:12

mo_shun


People also ask

How to count the number of occurrences in a list?

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 number of occurrences in a pandas Dataframe?

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?

How to count the number of occurrences of X in Python?

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.

How to increase the counter of a dictionary?

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!


1 Answers

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
like image 192
Haleemur Ali Avatar answered Oct 05 '22 15:10

Haleemur Ali