Python – lambda function using the example of searching in a list from dictionaries

Function lambda in Python for those who want brevity and do not want to paint functions. It is believed that it is better to take out the function, but sometimes it is more convenient to use lambda

Example 1

An example of an excerpt from the class below on starting data analysis timers.

class Timer:

def __init__(self):
selfdefault = [
            {‘name’: ‘change_percent’, ‘title’: ‘Изменение процента’},
            {‘name’: ‘change_price’, ‘title’: ‘Изменение цены’},
            {‘name’: ‘analyse_sp500’, ‘title’: ‘Анализ SP&500’},
            {‘name’: ‘brent_oil’, ‘title’: ‘Анализ нефти’},
        ]

def save_user_timer(self, user_id, name, timer, percent):
# If the name is not included in the default parameters
default = selfdefault
if not list(filter(lambda setting: setting[‘name’] == name, default)):
return

In the initialization of the class there is a variable (self.default) with sheet (list), which contains dictionaries (dic).

In the function of saving new data for the timer (save_user_timer), we will check the user’s incoming data for the presence of a mandatory match with the keys in the field name

In other words, if from the frontend to a variable name received a value different from any of the value of the name variable self.default, then we will interrupt the function without passing anything.

We know that such an event can happen mainly only in case of hacking attempts through sql injection and therefore we do not even warn why the request did not pass, but only interrupt.

Example 2

We get the first list with dictionaries:

query = db.sessionquery(Operation)filter_by(user_id=1)
operations = [x.serialize for x in query.all()]

In a variable operations there will be a list of dictionaries of this kind:

[{‘name’: ‘Genuine Parts’,
‘operation_type’: ‘Sell’,
‘payment’: 367.92,
‘price’: 91.98,
‘quantity’: 4,
‘user_id’: 1},…]

Next, we get the second list with dictionaries:

markets = [r._asdict() for r in db.session.query(MarketShort.name, MarketShort.last_price).all()]

It contains the following data:

[{‘name’: ‘Netflix’, ‘last_price’: 526.59}, {‘name’: ‘Spirit Airlines Inc’, ‘last_price’: 18.75},…]

Find a name match in the list of dictionaries “operations” in the list of dictionaries “markets”:

for operation in operations:
matched = list(filter(lambda market: market[‘name’] == operation[‘name’], markets))

# If there is a match, save the name:

if matched:
operation[‘last_price’] = matched[0][‘last_price’]</ div>

Ultimately, we will get a reworked list with dictionaries in which new data will be added:

[{‘name’: ‘Moderna Inc’,
‘operation_type’: ‘Buy’,
‘payment’: -687.0,
‘price’: 68.7,
‘last_price’: 67.83,
‘quantity’: 10,
‘user_id’: 1},…]

Note that added ‘last_price’: 67.83

All code with function:

def get_all_operations():
# Get the list of operations
query = db.sessionquery(Operation)filter_by(user_id=flask_login.current_userid)
operations = [x.serialize for x in query.all()]

# Get a list of markets
markets = [r._asdict() for r in db.session.query(MarketShort.name, MarketShort.last_price).all()]

# Find a name match in the “operations” dictionaries list in the “markets” dictionaries list
for operation in operations:
matched = list(filter(lambda market: market[‘name’] == operation[‘name’], markets))

# If there is a match, save the name
if matched:
operation[‘last_price’] = matched[0][‘last_price’]

return json.dumps(operations)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *