如何在python中从字典列表中获取前三名
大家好如何在python中从字典列表中获取前三名,python,list,dictionary,Python,List,Dictionary,大家好 resp = [{**"NR": "0"**,"Code": "4_RESOURCE","Cnt": "11"}, {"NR": "10","Code": "10_humans","Cnt": "1"},
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"}]
由此可知,如果上述字典列表中唯一代码的“NR”为“0”,则需要进行计数,并将该计数与唯一代码相加。那样的话,我们需要做三件事。它应该在字典中,如输出示例所示
输出样本:Cnt计数
{“4_资源”:26(15+11),“4_资源”:15,“10_人类”: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)
提前感谢使用a及其方法:
我无法将所需的输出(不是有效的Python数据结构)映射到您的描述。它不应该是
{'4_资源:26,'50_动物:20,'10_人类:12}
?
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}