Last active
December 14, 2015 00:39
-
-
Save diezguerra/5000803 to your computer and use it in GitHub Desktop.
How to filter dicts in python, the right way.
This file contains 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
# -*- coding: utf-8 -*- | |
# <nbformat>3.0</nbformat> | |
# <rawcell> | |
# How to filter Python dictionaries, the right way. | |
# | |
# Expected output: | |
# Original list lookup => 100 loops, best of 3: 9.82 ms per loop | |
# Dict trick lookup => 1000 loops, best of 3: 315 us per loop | |
# | |
# The Pythonic Way => 1000 loops, best of 3: 226 us per loop | |
# <codecell> | |
# Original look-up in list | |
import uuid | |
default_cols_list = [str(uuid.uuid4()) for _ in range(10 ** 3)] | |
dummy_data = dict([(item, None) for item in default_cols_list]) | |
print "Original list lookup =>", | |
%timeit dict([(key, value) for key, value in dummy_data.iteritems() if key in default_cols_list]) | |
# Second try, dict trick | |
default_cols_dict = dict([(item, 1) for item in default_cols_list]) | |
print "Dict trick lookup =>", | |
%timeit dict([(key, value) for key, value in dummy_data.iteritems() if key in default_cols_dict]) | |
# The pythonic way: | |
print "\nThe Pythonic Way =>", | |
%timeit {key: value for key, value in dummy_data.iteritems() if key in dummy_data} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment