take the first x elements of a dictionary on python

前提是你 提交于 2020-12-29 12:11:56

问题


I am a newbie on python, so I try to take the first 50 elements of a dictionary in python. I have a dictionary which is decreasing order sorted by value.

k=0
l=0
for k in len(dict_d):
    l+=1
    if l<51:
        print dict

for a small example:

 dict_d={'m':'3','k':'4','g':'7','d':'9'}

take the first 3 elements in a new dictionary:

 new_dict={'m':'3','k':'4','g':'7'}

I could not find how to do that?


回答1:


dict_d = {...}
for key in sorted(dict_d)[:50]:
    print key, dict_d[key]



回答2:


You can take 50 arbitrary elements (they have no order unless you were using an OrderedDict

>>> from itertools import islice
>>> d = dict.fromkeys(range(-50, 50))
>>> list(islice(d, 50))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]

I used the example range(-50, 50) to show the order is unreliable




回答3:


Just a quick for loop with a counter should do the trick:

count = 0
for key in my_dict:
    if count < 50:
        print my_dict[key]
    count += 1



回答4:


Contrast this with @jamylak's answer which just gives you 50 keys with no extra control. Here you can get the smallest 50 keys

>>> d = dict.fromkeys(range(-50, 50))
>>> import heapq
>>> heapq.nsmallest(50, d)
[-50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1]

You can order by a different critera by supplying key=func to heapq.nsmallest

>>> heapq.nsmallest(50, d, key=str)
[-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -3, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -4, -40, -41, -42, -43, -44, -45, -46, -47, -48, -49, -5, -50, -6, -7, -8, -9]



回答5:


Sort and get top 10 elements:-

from collections import Counter
dict(Counter(word_freq_dict).most_common(10))


来源:https://stackoverflow.com/questions/16976096/take-the-first-x-elements-of-a-dictionary-on-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!