如何计算字典列表中出现的值? [英] How can I count occurrences of values in a list of dicts?

查看:39
本文介绍了如何计算字典列表中出现的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典列表:

[{'Description': 'LARCENY'}, {'Description': 'LARCENY'}, {'Description': 'BURGLARY'}, {'Description': 'ROBBERY - STREET'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'AUTO THEFT'}, {'Description': 'AUTO THEFT'}, {'Description': 'ROBBERY - STREET'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'BURGLARY'}, {'Description': 'BURGLARY'}, {'Description': 'LARCENY'}, {'Description': 'ROBBERY - COMMERCIAL'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}]

我需要提供一个对这些词典进行迭代的函数,并计算每种类型的犯罪发生了多少次.输出应该是这样的字典列表:

I need to make a function that iterates over those dictionaries and counts how many times each type of crime has occurred. The output should be a list of dicts like this:

[{'LARCENY' : 3}, {'BURGLARY' : 2}, {'ROBBERY - STREET' : 3}...

对于每种类型的犯罪,我需要知道该犯罪发生了多少次. 这是我到目前为止的内容:

For each type of crime, I need to know how many times that crime as occurred. This is what I have so far:

result = {}
for k in data:
   if 'Description' in k:
    result[k['Description']] = result.get(k['Description'], 0) + 1 

但是给定的输出使我在同一个字典中拥有所有内容,但我希望它们出现在字典列表中,每个犯罪都伴随着每个字典.

But the output given gives me everything in the same dict, but I want them to be in a list of dicts, each crime with each dict.

如果您不了解我的知识,请随时提出任何问题.

Feel free to ask any question if you don't understand mine.

推荐答案

给出到目前为止的结果...

Given the result you've got so far...

>>> result = {'LARCENY' : 3, 'BURGLARY' : 2, 'ROBBERY - STREET' : 3}
>>> result = [{k:v} for k,v in result.items()]
>>> result
[{'BURGLARY': 2}, {'LARCENY': 3}, {'ROBBERY - STREET': 3}]

这篇关于如何计算字典列表中出现的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆