Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add select_keys. #393

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions toolz/dicttoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,21 @@ def get_in(keys, coll, default=None, no_default=False):
if no_default:
raise
return default


def select_keys(d, keys, factory=dict):
""" Select only certain keys from a dictionary

If supplied keys are not found in the dictionary, returns an empty
dictionary.

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> select_keys(d, ['a', 'b', 'd'])
{'a': 1, 'b': 2}
>>> select_keys(d, ['d'])
{}
"""
rv = factory()
for k in set(keys).intersection(d.keys()):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recommend spelling this out explicitly for performance reasons:

for k in keys:
    if k in d:
        rv[k] = d[k]

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.

rv[k] = d[k]
return rv
15 changes: 12 additions & 3 deletions toolz/tests/test_dicttoolz.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from collections import defaultdict as _defaultdict
from toolz.dicttoolz import (merge, merge_with, valmap, keymap, update_in,
assoc, dissoc, keyfilter, valfilter, itemmap,
itemfilter, assoc_in)
from toolz.dicttoolz import (assoc, assoc_in, dissoc, itemfilter,
itemmap, keyfilter, keymap, merge,
merge_with, select_keys, update_in,
valfilter, valmap)
from toolz.utils import raises
from toolz.compatibility import PY3

Expand Down Expand Up @@ -117,6 +118,14 @@ def test_assoc_in(self):
assert d is oldd
assert d2 is not oldd

def test_select_keys(self):
D, kw = self.D, self.kw
assert select_keys(D({}), [], **kw) == D({})
assert select_keys(D({"a": 1}), ["a"], **kw) == D({"a": 1})
assert select_keys(D({"a": 1}), [], **kw) == D({})
assert select_keys(D({"a": 1}), ["b"], **kw) == D({})
assert select_keys(D({"a": 1, "b": 2}), ["b"], **kw) == D({"b": 2})

def test_update_in(self):
D, kw = self.D, self.kw
assert update_in(D({"a": 0}), ["a"], inc, **kw) == D({"a": 1})
Expand Down