This is about … .
Lambda
This is not specific to Python, but I have only practised this with this language so far.
Refer to the deathly hallows for the Counter, sorted and most_common usage example.
A very interesting thing that was suggested by ChatGPT when I was stuck on a problem (I didn’t want to use a big function):
list_of_val = [
{
"requests": 301,
"name": "something1"
},
{
"requests": 200,
"name": "something2"
}
]
result = max(enumerate(list_of_val), key=lambda x: x[1]['requests'])
It was a little challenging to grasp this from the first time. Here is a breakdown of the process:
enumerate(list_of_val)turns my list of values into the following list:
0 {'requests': 305, 'name': 'something1'}
1 {'requests': 13018, 'name': 'something2'}
- Then, the
map()function takes this new list, checks everyrequestsfieldkey=lambda x: x[1]['requests']and returns the index of the dictionary with the max value ofrequests. - The lamda part
key=lambda x: x[1]['requests']basically means the following: for each element in the enumerated list, take the value at index1(where a dictionary is stored), take item with the keyrequests
The print(max(array)) returns the max VALUE, whereas index, _ = max(enumerate(array)) returns the INDEX of the max element.
