Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

How to get top 3 count of names from list of dictionary in python

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

question from:https://stackoverflow.com/questions/65933417/how-to-get-top-3-count-of-names-from-list-of-dictionary-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...