I have two(n) Python dictionaries dict_1 = {"obj_value": 1, "other_key": 10}
and dict_2 = {"obj_value": 0, "other_key": 10}
and I need a rutine that returns the dictionary that minimizes the obj_value
key, in this case, dict_2
Any ideas about this problem without using conditionals (if)? I would want to extend this to more than two dictionaries.
CodePudding user response:
You can use min
min(dict1, dict2,.., key=lambda x : x.get("obj_value"))
Also if there are list of dictionaries then l_o_d = [{dict}] Then You can use
min(*l_o_d, key=lambda x : x.get("obj_value"))
CodePudding user response:
For the case of two dictionaries as you have it, a conditional is good enough:
chosen_dict = dict_1 if dict_1["object_value"] < dict_2["object_value"] else dict_2
For the general case, it depends a bit on the data structure you are using. Let's assume a simple extension with a list of dictionaries, like:
all_dictionaries = [
{"obj_value": 1, "other_key": 10},
{"obj_value": 0, "other_key": 10},
{"obj_value": 2, "other_key": 10},
...
{"obj_value": 999, "other_key": 10},
]
In this case you can simply sort the list by the key, like so:
chosen_dict = sorted(all_dictionaries, key=lambda x: x["obj_value"])[0]
This sorts the list by the key
attribute, with this picking out the value for the obj_value
in each dictionary, then we simply take the 0th element, which is a dictionary with the lowest value for the object_value
key.
You can do something similar with min
:
chosen_dict = min(all_dictionaries, key=lambda x: x["obj_value"])