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? 回答1: dict_d = {...} for key in sorted(dict_d)[:50]: print key, dict_d[key] 回答2: You can take 50 arbitrary