Logo
RSS Feed

Python Magic

Created: 28.07.2022

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:

  1. enumerate(list_of_val) turns my list of values into the following list:
0 {'requests': 305, 'name': 'something1'}
1 {'requests': 13018, 'name': 'something2'}
  1. Then, the map() function takes this new list, checks every requests field key=lambda x: x[1]['requests'] and returns the index of the dictionary with the max value of requests.
  2. The lamda part key=lambda x: x[1]['requests'] basically means the following: for each element in the enumerated list, take the value at index 1 (where a dictionary is stored), take item with the key requests

The print(max(array)) returns the max VALUE, whereas index, _ = max(enumerate(array)) returns the INDEX of the max element.

References

Expand… Something here