Created
August 7, 2018 16:31
-
-
Save shurph/eebee0053f22b1991eb440083c69acf9 to your computer and use it in GitHub Desktop.
how to filter keys in a dict
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
| #!/usr/bin/env python | |
| from operator import itemgetter | |
| # v1 | |
| def filter_dict_1(dict_obj, allowed_fields): | |
| getter = itemgetter(*allowed_fields) | |
| return dict(zip(allowed_fields, getter(dict_obj))) | |
| # v2 | |
| def filter_dict_2(dict_obj, allowed_fields): | |
| return dict((key, value) for key, value in dict_obj.items() if key in allowed_fields) | |
| # v3 | |
| def filter_dict_3(dict_obj, allowed_fields): | |
| return {key: value for key, value in dict_obj.items() if key in allowed_fields} | |
| # v4 | |
| def get_filter_dict_4(allowed_fields): | |
| getter = itemgetter(*allowed_fields) | |
| return lambda dict_obj, *a: dict(zip(allowed_fields, getter(dict_obj))) | |
| if '__main__' == __name__: | |
| keys = ('key_1', 'key_2', 'key_3') | |
| d = [{'key_%s' % i: j for i in range(10)} for j in range(1000000)] | |
| x = [filter_dict_1(x, keys) for x in d] | |
| x = [filter_dict_2(x, keys) for x in d] | |
| x = [filter_dict_3(x, keys) for x in d] | |
| filter_dict_4 = get_filter_dict_4(keys) | |
| x = [filter_dict_4(x, keys) for x in d] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment