[英]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? 我已经使用Counter()
和most_common(n)
来计算所有密钥,但是如何找到特定密钥的计数呢? 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: “条目”数据大约有60k条目,如下所示:
[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]
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
对于特定的艺术家,您可以将if k.get('artist')
替换为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 3rd Edit :如果您对理解或生成器不满意,或者感觉增强了代码的可读性,则也可以循环
n = 0 # number of artists
for k in entries:
n += 1 if k.get('artist') == artist_pick else 0
You can add Counter
objects together with +
. 您可以将Counter
对象与+
一起添加。 Below is a demonstration: 下面是一个演示:
>>> from collections import Counter
>>> data = [{'a':1, 'b':1}, {'a':1, 'c':1}, {'b':1, 'c':1}, {'a':1, 'c':1}, {'a':1, 'd':1}]
>>> counter = Counter(data[0])
>>> for d in data[1:]:
... counter += Counter(d)
...
>>> counter
Counter({'a': 4, 'c': 3, 'b': 2, 'd': 1})
>>> counter['a'] # Count of 'a' key
4
>>> counter['d'] # Count of 'd' key
1
>>>
Or, if you want to get fancy, replace the for-loop with sum
and a generator expression: 或者,如果您想花哨的话,请用sum
和一个生成器表达式替换for循环:
>>> from collections import Counter
>>> data = [{'a':1, 'b':1}, {'a':1, 'c':1}, {'b':1, 'c':1}, {'a':1, 'c':1}, {'a':1, 'd':1}]
>>> counter = sum((Counter(d) for d in data[1:]), Counter(data[0]))
>>> counter
Counter({'a': 4, 'c': 3, 'b': 2, 'd': 1})
>>>
I personally prefer the readability of the for-loop though. 我个人更喜欢for循环的可读性。
If you mean to count the keys rather than the distinct values to a particular key, then without Counter()
: 如果您打算计算键而不是特定键的不同值,则不使用Counter()
:
artist_key_count = 0
for track in entries:
if 'artist' in track.keys():
artist_key_count += 1
If you mean to count the number of times each artist appears in your list of tracks, you can also do this without Counter()
: 如果要计算每个艺术家出现在曲目列表中的次数,也可以不使用Counter()
来执行此操作:
artist_counts = {}
for track in entries:
artist = track.get('artist')
try:
artist_counts[artist] += 1
except KeyError:
artist_counts[artist] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.