def get_item(ld, key, value, default = None):
for item in ld:
if item[key] == value:
return item
return default
a = [ { n: 0 }, { n: 1 } ]
print(get_item(a, 'n', 1)) # { n: 1 }
print(get_item(a, 'n', 5)) # None
def get_item(ld, predicate, default = None):
for item in ld:
if predicate(item):
return item
return default
print(get_item(a, lambda item: item['n'] == 1)) # { n: 1 }
print(get_item(a, lambda item: item['n'] == 5)) # None
class MyList(list):
RAISE = object()
def intersect(self, dct, default=RAISE):
for item in self:
if all(item[k] == v for k, v in dct.items()):
return item
if default is self.RAISE:
raise ValueError("Couldn't find")
else:
return default
In [6]: l = MyList([{'city': 'moscow', 'name': 'Roman'}])
In [7]: l.intersect({'city': 'moscow'})
Out[7]: {'city': 'moscow', 'name': 'Roman'}
In [8]: l.intersect({'city': 'tomsk'})
ValueError: Couldn't find
>>> lst = [{'n': 0}, {'n': 1}]
>>>
>>> next(filter(lambda i: i['n'] == 1, lst), None)
{'n': 1}
>>> next(filter(lambda i: i['n'] == 5, lst), None)
>>>
>>> lst = [{'n': 0}, {'n': 1}]
>>>
>>> next((i for i in lst if i['n'] == 1), None)
{'n': 1}
>>> next((i for i in lst if i['n'] == 5), None)
>>>