![](/img/trans.png)
[英]Count occurrences of specific dict value in list of dicts and create a new dict with that count
[英]How to count occurrences of specific dict key in list of dicts
我正在尝试计算在我的字典列表中出现指定键的次数。 我已经使用Counter()
和most_common(n)
来计算所有密钥,但是如何找到特定密钥的计数呢? 我有此代码,当前无法使用:
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]
“条目”数据大约有60k条目,如下所示:
[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]
您可以提取它,将其放入列表中,然后计算列表的长度。
key_artists = [k['artist'] for k in entries if k.get('artist')]
len(key_artists)
编辑 :如果数据很大,使用生成器表达式可能会更好:
key_artists = (1 for k in entries if k.get('artist'))
sum(key_artists)
第二次编辑 :
对于特定的艺术家,您可以将if k.get('artist')
替换为if k.get('artist') == artist_pick
3rd Edit :如果您对理解或生成器不满意,或者感觉增强了代码的可读性,则也可以循环
n = 0 # number of artists
for k in entries:
n += 1 if k.get('artist') == artist_pick else 0
您可以将Counter
对象与+
一起添加。 下面是一个演示:
>>> 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
>>>
或者,如果您想花哨的话,请用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})
>>>
我个人更喜欢for循环的可读性。
如果您打算计算键而不是特定键的不同值,则不使用Counter()
:
artist_key_count = 0
for track in entries:
if 'artist' in track.keys():
artist_key_count += 1
如果要计算每个艺术家出现在曲目列表中的次数,也可以不使用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.