Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

take the first x elements of a dictionary on python

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?

like image 261
user951487 Avatar asked Jun 07 '13 04:06

user951487


1 Answers

dict_d = {...}
for key in sorted(dict_d)[:50]:
    print key, dict_d[key]
like image 161
falsetru Avatar answered Nov 11 '22 17:11

falsetru