From e9c65dee7382f5f2220074d1ee20f41fec48c7e0 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Wed, 31 Mar 2021 10:59:21 +0200 Subject: [PATCH] documenting and testing --- python/damask/util.py | 52 ++++++++++++++++++++++++++------------- python/tests/test_util.py | 22 +++++++++++++++++ 2 files changed, 57 insertions(+), 17 deletions(-) diff --git a/python/damask/util.py b/python/damask/util.py index 735db39a0..b79df193a 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -399,34 +399,52 @@ def DREAM3D_cell_data_group(fname): return cell_data_group -def dict_strip(a_dict): + +def dict_strip(d): + """ + Remove recursively empty dictionaries. + + Parameters + ---------- + d : dict + dictionary. + + """ # https://stackoverflow.com/questions/48151953 - new_dict = {} - for k, v in a_dict.items(): + new = {} + for k,v in d.items(): if isinstance(v, dict): v = dict_strip(v) if not isinstance(v,dict) or v != {}: - new_dict[k] = v - return new_dict + new[k] = v + return new -def dict_compress(a_dict): - # https://stackoverflow.com/questions/48151953 - if isinstance(a_dict,dict) and len(a_dict) == 1: - key = list(a_dict.keys())[0] - entry = a_dict[key] +def dict_compress(d): + """ + Remove recursively dictionaries with one entry. + + Parameters + ---------- + d : dict + dictionary. + + """ + if isinstance(d,dict) and len(d) == 1: + key = list(d.keys())[0] + entry = d[key] if isinstance(entry,dict): - new_dict = dict_compress(entry.copy()) + new = dict_compress(entry.copy()) else: - new_dict = entry + new = entry else: - new_dict = {} - for k, v in a_dict.items(): + new = {} + for k,v in d.items(): if isinstance(v, dict): v = dict_compress(v) - if not isinstance(v,dict) or v != {}: - new_dict[k] = v - return new_dict + if not isinstance(v,dict) or v == {}: + new[k] = v + return new diff --git a/python/tests/test_util.py b/python/tests/test_util.py index b96908a9a..500e7d733 100644 --- a/python/tests/test_util.py +++ b/python/tests/test_util.py @@ -136,3 +136,25 @@ class TestUtil: else: with pytest.raises(ValueError): util.DREAM3D_cell_data_group(tmp_path/'cell_data_group.dream3d') + + + @pytest.mark.parametrize('full,reduced',[({}, {}), + ({'A':{}}, {}), + ({'A':{'B':{}}}, {}), + ({'A':{'B':'C'}},)*2, + ({'A':{'B':{},'C':'D'}}, {'A':{'C':'D'}})]) + def test_strip(self,full,reduced): + assert util.dict_strip(full) == reduced + + + @pytest.mark.parametrize('full,reduced',[({}, {}), + ({'A':{}}, {}), + ({'A':'F'}, 'F'), + ({'A':{'B':{}}}, {}), + ({'A':{'B':'C'}}, 'C'), + ({'A':1,'B':2},)*2, + ({'A':{'B':'C','D':'E'}}, {'B':'C','D':'E'}), + ({'B':'C','D':'E'},)*2, + ({'A':{'B':{},'C':'D'}}, {'B':{},'C':'D'})]) + def test_compress(self,full,reduced): + assert util.dict_compress(full) == reduced