Created
January 19, 2018 08:55
-
-
Save takemikami/8501124b7db5253fe355c5cd031cf976 to your computer and use it in GitHub Desktop.
python idioms for list[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
| sample = [ | |
| {'name': 'hoge', 'val1': 10}, | |
| {'name': 'fuga', 'val1': 30}, | |
| ] | |
| # filter #1 | |
| filter(lambda x: x['val1'] > 20, sample) | |
| # => [{'val1': 30, 'name': 'fuga'}] | |
| # filter #2 | |
| [x for x in sample if x['val1'] > 20] | |
| # => [{'val1': 30, 'name': 'fuga'}] | |
| # sort | |
| sorted(sample, key=lambda x: x['name']) | |
| # => [{'val1': 30, 'name': 'fuga'}, {'val1': 10, 'name': 'hoge'}] | |
| # transform to dict[dict] | |
| dict([(x['name'], x) for x in sample]) | |
| # => {'fuga': {'val1': 30, 'name': 'fuga'}, 'hoge': {'val1': 10, 'name': 'hoge'}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment