I have a dictionary with either a integer or a tuple of integers as value. How do I fin开发者_开发技巧d the maximum integer present in dicts' values?
Example:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
should return 3 and
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
should return 5
A one-liner:
max(max(v) if isinstance(v, collections.Iterable) else v for v in d.itervalues())
Needs at least Python 2.6 due to collections.Iterable
ABC.
max(max(k,max(v) if isinstance(v,collections.Iterable) else v) for k,v in x1.items())
The other one-liner does not take account of the keys.
This is icky because it is not the designed use of a dictionary: the keys are meant to be keys, not themselves stores of data. I think you should reconsider your data structure.
EDIT: The above was nonsense. Thanks to @SilentGhost for pointing it out.
This is my version of one liner not needing 2.6:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
print max(max(values) if hasattr(values,'__iter__') else values for values in x1.values())
print max(max(values) if hasattr(values,'__iter__') else values for values in x2.values())
Output:
3
5
HOWEVER I strongly suggest to go to origin of these values and change the storing of integers to singleton tuples.Then you can use cleaner code:
x1 = {0:(2,), 2:(1,), 3:(1, 2), 20:(3,)}
x2 = {0:(2,), 2:(1,), 3:(1, 5), 20:(3,)}
for x in (x1,x2):
print max(max(values) for values in x.values())
You could try this aproach:
- create a set for storing integers
- loop through the values of the dictionary
- add integer values to set
- add each integer value of tuple values to set
- find max of set
Something like this:
def maxofdict(x):
s = set()
for v in x.values():
if hasattr(v, '__len__'):
s.update(v)
else:
s.add(v)
return max(s)
You need a generic flatten()
function. The Python standard library oddly enough doesn't provide one -- not even in itertools
-- but googling around should get you an implementation. If you don't mind being potentially backwards incompatible, you can import
a "private" implementation from tkinter
:
from _tkinter import _flatten as flatten
def mixed_max(d):
return max(flatten(d.items()))
mixed_max({0: 2, 2: 1, 3: (1,2), 4: 0}) # => 4
mixed_max({0: 2, 2: 1, 3: (1,5), 4: 0}) # => 5
Assuming the correct result for x1 = 4;
def maxOfMixedDict(x):
max = 0
for key, value in x.items():
if(key > max):
max = key
try:
for v2 in value:
if(v2 > max):
max = v2
except TypeError, e:
pass
return max
精彩评论