Suppose that I have the following dictionary:
d = {'q' : 2,
'b': 22,
'c': 19,
'e': 3,
'd': 9}
What I want to do is to iteratively remove the smallest values (with their keys) from the dictionary. For instance, if I want to remove 2 smallest values, I expect to obtain the following as remaining dictionary:
d = {'b': 22,
'c': 19,
'd': 9}
Note that the ordering matters for me in this case. That is, the items in the original dictionary should NOT be reordered after processing.
I tried the below code, but it does not work for an example where dict's length is 19, and I need to remove 18 least values (w/ their associated keys).
def remaining(dict, smallest_n):
remaining = dict
s = {}
for i in range(smallest_n-1):
m = min(remaining.values())
for k, v in remaining.items():
if v != m:
s[k] = v
remaining = s.copy()
s.clear()
return remaining
For the case I mentioned above, when the smallest_n
(which is the number of minimum elements that should be removed) equals to 18, and the input dictionary's size is 19, what I obtain as remaining should have size 1 (19-18). However, it doesn't contain anything after the code lines are being executed.