Hello guys,
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" is "0" from unique Code from the above list of dictionary then need to take count and add that count against the unique code. like that need to take top three counts. it should be in dictionary as shown in output sample
output sample: count of Cnt {"4_RESOURCE": 26(15+11), "4_RESOURCE": 15, "10_humans":12}
-------[Top three in dictionary]
I tired:
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
Use a collections.Counter
and its most_commons
method:
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}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments