From 30a7bd9eb2effacb8ff4c80a10ab7156a243b9da Mon Sep 17 00:00:00 2001 From: Ian Lin Date: Thu, 15 Dec 2016 17:32:57 +0800 Subject: [PATCH] path reducer --- flatten_dict/flatten_dict.py | 3 ++- flatten_dict/reducer.py | 7 +++++++ flatten_dict/tests.py | 5 +++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/flatten_dict/flatten_dict.py b/flatten_dict/flatten_dict.py index 81f3a9b..3944c42 100644 --- a/flatten_dict/flatten_dict.py +++ b/flatten_dict/flatten_dict.py @@ -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): diff --git a/flatten_dict/reducer.py b/flatten_dict/reducer.py index 8cd0428..93f7f10 100644 --- a/flatten_dict/reducer.py +++ b/flatten_dict/reducer.py @@ -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) diff --git a/flatten_dict/tests.py b/flatten_dict/tests.py index 01a8948..e74a5b7 100644 --- a/flatten_dict/tests.py +++ b/flatten_dict/tests.py @@ -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