Reputation: 10300
I have a dict with tuples as keys, and I want to obtain the largest value available, say for the second element of the tuple keys currently in the dictionary. For example, given:
my_dict = {('a', 1):value_1, ('b', 1):value_2, ('a', 2):value_3, ('c', 3):value_4, ('b', 2):value_5}
so the largest value for the second elements of the keys is 3.
What is the fastest way to derive this value?
Upvotes: 1
Views: 1506
Reputation: 24788
Either:
largest_key = max(my_dict, key=lambda x: x[1])
Or:
from operator import itemgetter
largest_key = max(my_dict, key=itemgetter(1))
According to DSM, iterating over a dict
directly is faster than retrieving and iterating over keys()
or viewkeys()
.
What I think Ms. Zverina is talking about is converting your data structure from a dict
with tuple
keys to something like this:
my_dict = {
'a': {
1: value_1,
2: value_3
}
'b': {
1: value_2,
2: value_5
}
'c': {
3: value_4
}
}
That way, if you wanted find the max of all values with a
, you could simply do:
largest_key = max(d['a'])
At no extra cost. (Your data is already divided into subsets, so you don't have to waste computation on building subsets each time you do a search).
EDIT
To restrict your search to a given subset, do something like this:
>>> subset = 'a'
>>> largest_key_within_subset = max((i for i in my_dict if i[0] == subset), key=itemgetter(1))
Where (i for i in my_dict if i[0] == subset)
is a generator that returns only keys that are in the given subset.
Upvotes: 5
Reputation: 1080
If you have no additional information about any relation between elements in any set (like keys in dictionary in that case) then you have to check each element => complexity O(n)
(linear) - the only improvement can be using some build-in function like max
If you need quite often to obtain (or pop) max value then think about different structure (like heap
).
Upvotes: 1
Reputation: 11163
If you looking for largest value i.e. 3 use this:
print max(my_dict.keys(), key = lambda x: x[1])[1]
If you are looking for largest value from the dict, use this:
my_dict = {('a', 1):'value_1', ('b', 1):'value_2', ('a', 2):'value_3', ('c', 3):'value_4', ('b', 2):'value_5'}
largest = max(my_dict.keys(), key = lambda x: x[1])
print my_dict[largest]
Upvotes: 1