Skip to content

Commit

Permalink
path reducer
Browse files Browse the repository at this point in the history
  • Loading branch information
ianlini committed Dec 15, 2016
1 parent cca8044 commit 30a7bd9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion flatten_dict/flatten_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

import six

from .reducer import tuple_reducer
from .reducer import tuple_reducer, path_reducer


REDUCER_DICT = {
'tuple': tuple_reducer,
'path': path_reducer,
}

def flatten(d, reducer='tuple', inverse=False):
Expand Down
7 changes: 7 additions & 0 deletions flatten_dict/reducer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,10 @@ def tuple_reducer(k1, k2):
return (k2,)
else:
return k1 + (k2,)

def path_reducer(k1, k2):
import os.path
if k1 is None:
return k2
else:
return os.path.join(k1, k2)
5 changes: 5 additions & 0 deletions flatten_dict/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,8 @@ def test_flatten_dict_inverse():

def test_flatten_dict_with_reducer():
assert flatten(normal_dict, reducer=tuple_reducer) == flat_normal_dict

def test_flatten_dict_path():
from os.path import join
flat_path_dict = {join(*k): v for k, v in six.viewitems(flat_normal_dict)}
assert flatten(normal_dict, reducer='path') == flat_path_dict

0 comments on commit 30a7bd9

Please sign in to comment.