MaverickD
MaverickD

Reputation: 1657

how to get key of item from list of dictionary when using generator expressions

I am trying to learn about generator expressions and how they work.

I have a list of dictionary like this,

la = [ {'app_name': 'MKV58YCF8RR','time_diff': 17647},
       {'app_name': 'ZXG68HYW4BA','time_diff': 18132}]

I wanted to get the maximum value of time_diff from it, which I did using max

max_val = max(value["time_diff"] for value in la)

This gives me,

18132

But I want to also print the app_name of this time_diff.

Expected Output:

ZXG68HYW4BA is 18132

Current Output

18132

Can someone please tell me how can I also get the app_name key as well?

Edit:

I think I need to use map but not sure how?

Upvotes: 4

Views: 68

Answers (2)

Tomalak
Tomalak

Reputation: 338158

First determine the max value, like you did, then select the item that has this value:

max_time_diff = max(item["time_diff"] for item in la)
max_item = next(item for item in la if item["time_diff"] == max_time_diff)

next() picks the next item from an iterable.

In this particular case that iterable is exactly one item long, but in theory there could be more than one item that has a time_diff equal to max_time_diff, so next() makes sure that only the first matching item is picked.

Upvotes: 2

timgeb
timgeb

Reputation: 78670

Use max on la and provide a callable key such that you get the whole dictionary with the highest value for time_diff.

>>> la = [{'app_name': 'MKV58YCF8RR','time_diff': 17647},
...        {'app_name': 'ZXG68HYW4BA','time_diff': 18132}]
>>> 
>>> max_d = max(la, key=lambda d: d['time_diff']) # dict with max time_diff
>>> print('{d[app_name]} is {d[time_diff]}'.format(d=max_d))
ZXG68HYW4BA is 18132

thank you, i don't understand how lambda is working here if there is no loop to iterate entire list.

Don't get distracted by the lambda. It is used as a criterion by which to select the maximum value of la, but we can write is as a normal function just as well.

>>> def criterion(dictionary):
...     return dictionary['time_diff']
... 
>>> max(la, key=criterion)
{'app_name': 'ZXG68HYW4BA', 'time_diff': 18132}

max iterates la, calls criterion with every element of la, and returns the element of la where criterion is maximal.

can I extract it just like you did with lambda, while using itemgetter instead?

Sure!

>>> import operator
>>> max_d = max(la, key=operator.itemgetter('time_diff'))
>>> print('{d[app_name]} is {d[time_diff]}'.format(d=max_d))
ZXG68HYW4BA is 18132

Upvotes: 4

Related Questions