Suppose you have a class Table which contains the attribute: records (list of dictionaries) and keys which is the primary key of each table (just like SQL) - Tuple
I need to write a lambda function that takes a new row and then spit out True or False if all the values of the keys in the new row are already in the table
For example:
# Table: orders
keys = ('product_id', 'customer_id')
records: [{'product_id': 51, 'customer_id' : 10, 'units':9},
{'product_id': 32, 'customer_id' : 11, 'units':33},
{'product_id': 39, 'customer_id' : 47, 'units':2}]
and now the new row we want to check is:
{'product_id': 51, 'customer_id' : 10, 'units': 77 }
This would return True because product_id==51 and customer_id==10 just like the first dictionary in the record (the units does not matter, because its not a key).
However this:
{'product_id': 51, 'customer_id' : 11, 'units':9}
Will return False because there is no row with product_id==51 and customer_id==11
We must use lambda functions (we don't have to use filter, just a hint)
I've tried many many different ways of 'attacking' this question, but I couldn't iterate over a list of keys and a tuple at the same time...
contains_key = lambda self, new_row: list(filter(
(lambda con: con[self.__key]),
[record for record in self.__records]
))
Explanation: self is the table we do the operation on, new_row is the row (dictionary) to check
self.__keys is the tuple of keys (like primary keys in sql) and self.__records is the list of dictionaries="""rows in an sql table""")
The function is inside the class Table (that's why it's in the "self" form)
class Table:
def __init__(self, key_set):
self.__key = tuple(key_set)
self.__records = []
def add_record(self, new_record):
self.__records.append(new_record)
x = lambda ...kinda loses the point of lambdas...defis almost always better.