Supriya
Supriya

Reputation: 1941

Extracting max min where the value of each key is a dictionary

I have the following, where the value for each key is a dictionary itself:

dict = { "key1": { "sal":24000, "xy":32, "age":54}
         "key2": { "sal":40000, "xy":22, "age":14}
         "key3": { "sal":50000, "xy":12, "age":64} }

I want to extract the maximum and minimum salary from here. i.e my output should be 24000 when I search for the minimum and 50000 when I search for the maximum.

How do I go about this? Thank you.

Upvotes: 4

Views: 300

Answers (5)

Elliptica
Elliptica

Reputation: 4322

Another way is to use list comprehension to find the max/min of each inner dictionary, and then return the max/min of all of that:

MAX: max([max(dict[key].values()) for key in dict])

MIN: min([min(dict[key].values()) for key in dict])

Upvotes: 1

Netwave
Netwave

Reputation: 42746

You can extract both of them in a single call reducing the dict values:

>>> dict = { "key1": { "sal":24000, "xy":32, "age":54},
         "key2": { "sal":40000, "xy":22, "age":14},
         "key3": { "sal":50000, "xy":12, "age":64} }
>>>import sys
>>>max, min = reduce(lambda (max, min), v: (max if max > v else v, min if min < v else v), [e["sal"] for e in dict.values()], (0, sys.maxint))

>>> max
50000
>>> min
24000

Explaining the code above:

Lambda function that takes a tuple with the max and min and a value, changing the values of the tuple for the value taken if the conditions are passed.

lambda (max, min), v: (max if max > v else v, min if min < v else v)

Taking all the salaries from the dict into a list:

[e["sal"] for e in dict.values()]

Initial tuple values for the reduce method:

(0, sys.maxin)

reduce just takes values once after another feeding the lambda function.

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52183

Here is another way of getting the highest salary using operator.itemgetter:

max(dict.itervalues(), key=operator.itemgetter('sal'))

Extracting salaries first, then apply max:

max(d['sal'] for d in dict.itervalues())

Upvotes: 1

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85492

Full solution:

dic = {"key1": { "sal": 24000, "xy": 32, "age": 54},
       "key2": { "sal": 40000, "xy": 22, "age": 14},
       "key3": { "sal": 50000, "xy": 12, "age": 64} }

max_sal = max(dic.values(), key=lambda x: x['sal'])['sal']
min_sal = min(dic.values(), key=lambda x: x['sal'])['sal']

>>> max_sal
50000
>>> min_sal
24000

Note: Don't use dict as your variable name. It is a built-in.

Upvotes: 2

Eugene Primako
Eugene Primako

Reputation: 2817

max(dict.itervalues(), key=lambda x: x['sal'])

Just the same for minimum.

Upvotes: 3

Related Questions