如何从python的字典列表中获取前3个名称计数



大家好

resp = [{**"NR": "0"**,"Code": "4_RESOURCE","Cnt": "11"}, 
{"NR": "10","Code": "10_humans","Cnt": "1"},
{"NR": "1000","Code": "4_RESOURCE","Cnt": "120"}, 
{**"NR": "0"**,"Code": "10_humans","Cnt": "12"},
{**"NR": "0"**,"Code": "4_RESOURCE","Cnt": "15"},
{**"NR": "0"**,"Code": "50_animals","Cnt": "20"}]

from it, if "NR"0";从唯一的代码从上面的列表的字典,然后需要计数和添加计数对唯一的代码。就像这样,需要前三名。它应该在dictionary中,如输出示例

所示。输出示例:计数{"4_RESOURCE": 26(15+11), "4_RESOURCE": 15, "10_humans":12}-------[字典前三名]

我累了:

def se_conc(response):
cnt = 0
list = []
def key_func(k):
return k['Code']
INFO = sorted(resp, key=y_func)
for k, v in groupby(INFO, y_func):
print("codes:", k)
print("v:", v)
list.append(k)
print("listcode", list)
for key in list:
if resp['NR'] == "0":
print("NR is 0:", k)

Thanks in advance

使用collections.Counter及其most_commons方法:

from collections import Counter
c = Counter()
for d in resp:
if d["NR"] == "0":
c[d["Code"]] += int(d["Cnt"])
dict(c.most_common(3))
# {'4_RESOURCE': 26, '50_animals': 20, '10_humans': 12}

相关内容

  • 没有找到相关文章

最新更新