MUQ  0.4.3
PyDictConversion.h
Go to the documentation of this file.
1 #ifndef PYDICTCONVERSION_H
2 #define PYDICTCONVERSION_H
3 
4 #include <Python.h>
5 
6 #include <pybind11/pybind11.h>
7 #include <pybind11/stl.h>
8 #include <pybind11/eigen.h>
9 
10 #include <boost/property_tree/ptree.hpp>
11 #include <boost/property_tree/json_parser.hpp>
12 
13 namespace muq{
14  namespace Utilities{
15 
16  inline void AddDictToPtree(pybind11::dict dict, std::string basePath, boost::property_tree::ptree &pt)
17  {
18  pybind11::object keys = pybind11::list(dict.attr("keys")());
19  std::vector<std::string> keysCpp = keys.cast<std::vector<std::string>>();
20 
21  for(auto& key : keysCpp){
22 
23  // Recursively add dictionaries
24  if(pybind11::isinstance<pybind11::dict>(dict.attr("get")(key))){
25  AddDictToPtree(dict.attr("get")(key), basePath + key + ".", pt);
26 
27  // Convert lists in the comma-separated strings
28  }else if(pybind11::isinstance<pybind11::list>(dict.attr("get")(key))){
29  std::string val = "";
30  for(auto comp : pybind11::list(dict.attr("get")(key)))
31  val += "," + std::string(pybind11::str(comp));
32  pt.put(basePath + key, val.substr(1));
33 
34  // Add all the other objects through their "str" interpretation
35  }else{
36  if( ((std::string)pybind11::str(dict.attr("get")(key))).compare("False")==0 ) {
37  pt.put(basePath + key, false);
38  } else if( ((std::string)pybind11::str(dict.attr("get")(key))).compare("True")==0 ) {
39  pt.put(basePath + key, true);
40  } else {
41  pt.put(basePath + key, pybind11::str(dict.attr("get")(key)));
42  }
43  }
44  }
45  };
46 
67  inline boost::property_tree::ptree ConvertDictToPtree(pybind11::dict dict)
68  {
69  boost::property_tree::ptree pt;
70  AddDictToPtree(dict, "", pt);
71  return pt;
72  };
73 
74  }
75 }
76 
77 
78 #endif
void AddDictToPtree(pybind11::dict dict, std::string basePath, boost::property_tree::ptree &pt)
boost::property_tree::ptree ConvertDictToPtree(pybind11::dict dict)