I have a function that has a dictionary as input and a value n.
Each item in the dictionary is a set with one or more values.
The function should sort the dictionary keys and it should extract and return “n”values.
This function will be executed very often therefore I am trying to optimize it. Any suggestions?
def select_items(temp_dict, n):
"""Select n items from the dictionary"""
res = []
sort_keys = sorted(temp_dict.keys())
count = 0
for key in sort_keys:
for pair in temp_dict[key]:
if count < n:
res.append(pair)
count += 1
else:
return res
return res
In this code I have a count and “if statement” to control the number of selected values. Is there a way to optimize this code by using some function in itertools or something else?
The answers given so far don’t follow the user’s spec.
The data is a dictionary of sequences, and the desired result is a list of the first n elements of the dictionary values taken in sorted order by key.
So if the data is:
then, if n = 5, the result should be:
Given that, here’s a script which compares the original function with a (slightly) optimised new version:
Output: