From: Ondrej Lichtner <olichtne(a)redhat.com>
This adds a couple of utility functions useful when working with
PerfRepo.
recursive_dict_update
recursively updates nested dictionaries
dot_to_dict
parses a pair of dot separated keys into a dictionary hierarhy and
sets the value to the last key
dict_to_dot
reverse function to dot_to_dict, returns a list of (name, value)
pairs
list_to_dot
transforms a list of values to a list of (name, value) pairs where
the name contains dot separated keys, the last key is indexed with
the values index in the list
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
---
lnst/Common/Utils.py | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 52 insertions(+)
diff --git a/lnst/Common/Utils.py b/lnst/Common/Utils.py
index 19ac898..fb9d9a2 100644
--- a/lnst/Common/Utils.py
+++ b/lnst/Common/Utils.py
@@ -18,6 +18,7 @@ import tempfile
import subprocess
import errno
import ast
+import collections
from _ast import Call, Attribute
from lnst.Common.ExecCmd import exec_cmd
@@ -192,3 +193,54 @@ def get_module_tools(module_path):
f.close()
return tools
+
+def recursive_dict_update(original, update):
+ for key, value in update.iteritems():
+ if isinstance(value, collections.Mapping):
+ r = recursive_dict_update(original.get(key, {}), value)
+ original[key] = r
+ else:
+ original[key] = update[key]
+ return original
+
+def dot_to_dict(name, value):
+ result = {}
+ last = result
+ last_key = None
+ previous = None
+ for key in name.split('.'):
+ last[key] = {}
+ previous = last
+ last = last[key]
+ last_key = key
+ if last_key != None:
+ previous[last_key] = value
+ return result
+
+def list_to_dot(original_list, prefix="", key=""):
+ return_list = []
+ index = 0
+ for value in original_list:
+ iter_key = prefix + key + str(index) + '.'
+ index += 1
+ if isinstance(value, collections.Mapping):
+ sub_list = dict_to_dot(value, iter_key)
+ return_list.extend(sub_list)
+ elif isinstance(value, list):
+ raise Exception("Nested lists not allowed")
+ else:
+ return_list.append((iter_key, value))
+ return return_list
+
+def dict_to_dot(original_dict, prefix=""):
+ return_list = []
+ for key, value in original_dict.iteritems():
+ if isinstance(value, collections.Mapping):
+ sub_list = dict_to_dot(value, prefix + key + '.')
+ return_list.extend(sub_list)
+ elif isinstance(value, list):
+ sub_list = list_to_dot(value, prefix, key)
+ return_list.extend(sub_list)
+ else:
+ return_list.append((prefix+key, str(value)))
+ return return_list
--
2.1.0