Skip to content Skip to sidebar Skip to footer

Finding The Biggest Key In A Python Dictionary

General: I need help finding a way in python to get the max N items in a multi-dimensional python dictionary. For example: things = { 'car': { 'weight': 100 },

Solution 1:

You can simply use:

>>> sorted(things.keys(),key=lambda x:things[x]['weight'],reverse=True)
['car', 'spanner', 'apple']

To obtain a list of items sorted by their weight (here in reversed order such that the more heavy things are sorted first). So if you call:

>>> sorted(things.keys(),key=lambda x:things[x]['weight'],reverse=True)[:2]
['car', 'spanner']

you get the two heaviest. But this will run in O(n log n). In case the number of values k you wish to obtain is small (compared to the total number). You can use heapq:

from heapq import nlargest

result = nlargest(k,things.keys(),key=lambda x:things[x]['weight'])

which will - as far as I know - run in O(n log k) (k the numbers of items you want to pick).

Post a Comment for "Finding The Biggest Key In A Python Dictionary"