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 all 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
1 change: 1 addition & 0 deletions doc/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ Dicttoolz
keymap
merge
merge_with
select_keys
update_in
valfilter
valmap
Expand Down
19 changes: 19 additions & 0 deletions toolz/dicttoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,3 +337,22 @@ def get_in(keys, coll, default=None, no_default=False):
if no_default:
raise
return default


def select_keys(keys, d, 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(['a', 'b', 'd'], d) # doctest: +SKIP
{'a': 1, 'b': 2}
>>> select_keys(['d'], d)
{}
"""
rv = factory()
for k in keys:
if k in d:
rv[k] = d[k]
return rv
17 changes: 13 additions & 4 deletions toolz/tests/test_dicttoolz.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import os
from collections import defaultdict as _defaultdict
from collections.abc import Mapping
import os
from toolz.dicttoolz import (merge, merge_with, valmap, keymap, update_in,
assoc, dissoc, keyfilter, valfilter, itemmap,
itemfilter, assoc_in)
from toolz.functoolz import identity
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


Expand Down Expand Up @@ -119,6 +120,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(["a"], D({"a": 1}), **kw) == D({"a": 1})
assert select_keys([], D({"a": 1}), **kw) == D({})
assert select_keys(["b"], D({"a": 1}), **kw) == D({})
assert select_keys(["b"], D({"a": 1, "b": 2}), **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