I would like to filter a python dictionary to include only the minimum absolute values, returning a new dict with all key,value pairs which have the same min(abs())
match. I've coded up the following solution:
def return_closest_vals(dc):
# min_val = dc[min(dc, key=dc.get)]
min_val = 1e3
keys_matching_min_val = {}
for d, v in dc.items():
if abs(v) < min_val:
min_val = abs(v)
keys_matching_min_val = {d:v} # updating min_val means keys matchin are outdated. Reset with new val
elif abs(v) == min_val:
keys_matching_min_val[d] = v
return keys_matching_min_val
if __name__ == "__main__":
test_dict = {"a":1, "b":2, "c":-1, "d":2, "e":1}
expected_outcome = {"a":1, "c":-1, "e":1}
print(return_closest_vals(test_dict))
but I don't think it's very elegant. Is there any nicer way to do this?
CodePudding user response:
Solution that generates the correct output however it loops over the provided dictionary twice. If one pass is your requirement then your original solution is best.
def return_closest_vals(dc):
if not dc: return {}
min_val = min(abs(v) for v in dc.values())
return {k:v for k,v in dc.items() if abs(v) == min_val}
CodePudding user response:
I think you want something like
new_dict = {k: v for k,v in old_dict.items() if abs(v) == abs(min([*old_dict.values()]))}