简体   繁体   English

计算某种类型的词典数量

[英]Counting the number of dictionaries of a certain type

I have a list of dictionaries. 我有一个词典列表。 Each dictionary has a colour attribute. 每个字典都有一个颜色属性。 For example: 例如:

{'att1':value1, 'att2': value2, 'colour': 'Red'}

The colou attribute is from a list of 15 maxium colours. colou属性来自15种最大颜色的列表。

I have over a thousand of these dictionaries in the list. 我在列表中有超过一千个这样的词典。 I need to find out what is the popular colour and how many instances of it there are? 我需要找出流行的颜色是什么,有多少个实例? Simiilarly I need the second most popular colour, the number of instances of it, the third most, fourth most etc... Simiilarly我需要第二种最流行的颜色,它的实例数量,第三,最第四等...

Can some fancy pythonic syntax help me out? 一些花哨的pythonic语法可以帮助我吗?

from collections import defaultdict
colours = defaultdict(int)
for item in mylist:
   colours[item["colour"]] +=1

gives you a defaultdict with all the colours and their respective number. 为您提供所有颜色及其各自编号的defaultdict值。 Displaying those in a sorted fashion is trivial. 以排序的方式显示它们是微不足道的。

You could use Counter and generator like this: 您可以像这样使用Counter和generator:

distribution = collections.Counter(d['colour'] for d in list_of_dict)
distribution.most_common(2)

Use map to map each dictionary to its colors, then a collections.Counter . 使用map将每个字典映射到其颜色,然后使用collections.Counter Should be a one-liner this way. 这种方式应该是单行。 Something like 就像是

collections.Counter(map(lambda x: x.get("color"), listofdict))
l = []
for x in xrange(100):
   l.append({'att1':1, 'att2': 2, 'colour': 'Red'})

for x in xrange(10):
   l.append({'att1':1, 'att2': 2, 'colour': 'Blue'})

colors = [i['colour'] for i in l]

dcolors = {}
for i in colors:
   if not i in dcolors:
       dcolors[i] = 0
   dcolors[i] += 1

print dcolors

I created 100 red and 10 blue items, the print result is: 我创建了100个红色和10个蓝色项目,打印结果为:

{'Blue': 10, 'Red': 100}

You probably can find a way to find the max etc or sort it. 您可能会找到一种方法来查找最大值等或对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM