Reputation: 359
I've tried Googling this, but could not find an answer with regard to a situation similar to this one. I have a dictionary in the following format:
my_dict={'key1': ['some_data', 'some_more_data',6.0], 'key2': ['junk', 'some_more_junk',7.0], 'key3': ['something_good', 'good',1.0]}
How would I go about creating a subdictionary containing only the key-value pair with the smallest number at the end of the list? In other words, I'd want my output to be:
sub_dict={'key3': ['something_good','good',1.0]}
Note the minimum value will always be at the end of the list, the other elements in the list are pertinent to the key.
Upvotes: 2
Views: 848
Reputation: 19811
>>> min_value = sorted(my_dict.values(), key=lambda x: x[-1])[0][-1]
>>> {key: value for key, value in my_dict.items() if value[-1] == min_value}
{'key3': ['something_good', 'good', 1.0]}
First get the min_value
and the filter the dictionary in a way such that it gets all the key-value pairs which match the min_value
.
This will get all such key-value pairs where the last value is 1.0
.
You can also use min
to get the minimum value directly:
min_value = min(my_dict.values(), key=lambda x: x[-1])[-1]
Upvotes: 1
Reputation: 2596
Builtin min
function has key
keyword argument.
So you don't need to sort.
my_dict = {'key1': ['some_data', 'some_more_data', 6.0],
'key2': ['junk', 'some_more_junk', 7.0],
'key3': ['something_good', 'good', 1.0],
'key4': ['test', 'test', 1.0]}
min_value = min(my_dict.values(), key=lambda x: x[-1])[-1]
new_dict = {k: v for k, v in my_dict.items() if v[-1] == min_value}
print(new_dict)
output:
{'key3': ['something_good', 'good', 1.0], 'key4': ['test', 'test', 1.0]}
Upvotes: 2
Reputation: 16660
You can sort using a special sorting function that will get you the intended key - value pair from the dictionary as the first element:
sort_res = sorted(my_dict.items(), key=lambda kv: kv[1][-1])
k,v = list(sort_res)[0]
sub_dict = {k:v}
lambda kv: kv[1][-1]
returns the last element of the list and uses it for soring. Since it is operating on a pair of key and value there is kv[1]
which corresponds to the value.
Sorting gives us ordered pairs of key and value from the dictionary by the last element of the list. Then it is enough to take the first one and recreate a dictionary.
Warning: should there be more values on the original list that have the minimal value then you are going to get only one, arbitrary item of this value.
In such a case you can pick all of the items from the resulting list instead of picking only the first value:
lsort_res = list(sort_res)
res_dict = {}
minv = lsort_res[0][1][-1] # take the last element of the v list of the first k,v pair
for k,v in lsort_res:
if v[-1] == minv:
res_dict[k] = v
Upvotes: 1
Reputation: 1310
You can do in this way:
sub_dict={}
smallest = 999999
key=''
for k,v in my_dict.items():
if v[-1] < smallest:
smallest = v[-1]
key = k
sub_dict[key] = my_dict[key]
Upvotes: 0