take the first x elements of a dictionary on python
15,908
dict_d = {...}
for key in sorted(dict_d)[:50]:
print key, dict_d[key]
Related videos on Youtube
Author by
user951487
Updated on July 24, 2022Comments
-
user951487 almost 2 years
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?
-
user951487 almost 11 yearsI want to take only the first 50 elements not whole dictionary !
-
U2EF1 almost 11 yearsFor small dictionaries this is absolutely the pythonic way to do it. For larger ones though
itertools.islice(dict_d, 50)
is very much preferred.