-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_first.py
More file actions
27 lines (19 loc) · 835 Bytes
/
get_first.py
File metadata and controls
27 lines (19 loc) · 835 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from test_fixtures import countries
def get_first(iterable, value=None, key=None, default=None):
match value is None, callable(key):
case (True, True):
gen = (elem for elem in iterable if key(elem))
case (False, True):
gen = (elem for elem in iterable if key(elem) == value)
case (True, False):
gen = (elem for elem in iterable if elem)
case (False, False):
gen = (elem for elem in iterable if elem == value)
return next(gen, default)
if __name__ == "__main__":
print(get_first(countries))
target_match = {"country": "Norway", "population": 5_311_916}
print(get_first(countries, value=target_match))
def match_scotland(data):
return data["country"] == "Scotland"
print(get_first(countries, key=match_scotland))