Last active
November 7, 2022 19:53
-
-
Save coltenkrauter/1caecb8f0d5ef2a79400e8614cfe5f02 to your computer and use it in GitHub Desktop.
Python | Filter a list of dicts by dict field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pets = [ | |
{ | |
'id': '5460b046-5ed4-11ed-9b6a-0242ac120002', | |
'group': 'dog', | |
'type': 'German Shepherd', | |
'large': True, | |
}, | |
{ | |
'id': '90c5b2ca-5ed4-11ed-9b6a-0242ac120002', | |
'group': 'cat', | |
'type': 'Birman', | |
'large': False, | |
}, | |
{ | |
'id': '9bb4f448-5ed4-11ed-9b6a-0242ac120002', | |
'group': 'dog', | |
'type': 'Alaskan Malamute', | |
'large': True, | |
}, | |
] | |
# list comprehension | |
dogs = [pet for pet in pets if pet['group'] == 'dog'] | |
large_pets = [pet for pet in pets if pet['large']] | |
# filter | |
dogs = list(filter(lambda pet: pet['group'] == 'dog', pets)) | |
large_pets = list(filter(lambda pet: pet['large'], pets)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment