I have a dict, with strings as keys and lists as values and want to find the n keys with the longest lists (length).
How could I approach this problem?
I have a dict, with strings as keys and lists as values and want to find the n keys with the longest lists (length).
How could I approach this problem?
From here : I see you can build a sorted list from a dictionnary. That may not be the best way to do in terms of complexity.
here's with python 3 :
myDict = {'first':[1, 2, 3], 'second':[117, 2], 'third':[8, 37, 3, 4], 'fourth':[1], 'fifth': [3,2,3]}
for i in sorted(myDict, key = lambda x: len(myDict[x]), reverse=True):
print i, len(myDict[i])
and it prints out :
third 4
fifth 3
first 3
second 2
fourth 1
I don't know if that's what youre looking for, post more details for a more detailed answer.
If you have a dictionary as you described
>>> my_dict = {"first": [1, 2, 3], "second": [2, 3], "third": [1], "fourth": [1, 2, 3, 4]}
You can fetch the n longest values in the dictionary with something like:
>>> sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]
[('fourth', [1, 2, 3, 4]), ('first', [1, 2, 3])]
If you wanted the key names
>>> from operator import itemgetter
>>> tuple(map(itemgetter(0), sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]))
('fourth', 'first')
If you care about persistence, use an OrderedDict
>>> from collections import OrderedDict
>>> OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1])))
OrderedDict([('third', [1]),
('second', [2, 3]),
('first', [1, 2, 3]),
('fourth', [1, 2, 3, 4])])
To sort the key by order:
>>> tuple(OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1]))).keys())[::-1]
('fourth', 'first', 'second', 'third')