Translating python dictionary to C++
A dictionary would be a std::map in c++, and a tuple with two elements would be a std::pair.
The python code provided would translate to:
#include <iostream>
#include <map>
typedef std::map<std::pair<int, int>, int> Dict;
typedef Dict::const_iterator It;
int main()
{
Dict d;
d[std::make_pair(0, 0)] = 0;
d[std::make_pair(1, 2)] = 1;
d[std::make_pair(2, 1)] = 2;
d[std::make_pair(2, 3)] = 3;
d[std::make_pair(3, 2)] = 4;
for (It it(d.begin()); it != d.end(); ++it)
{
int i(it->first.first);
int j(it->first.second);
std::cout <<it->second <<' '
<<d[std::make_pair(j, i)] <<'\n';
}
}
Convert Python dictionary into C like structure
You can use PyDict_GetItem()
for that:
PyObject* pytab1 = PyDict_GetItemString(dict, "Tab1");
Since the result is a list, you can use these calls to examine it
This documentation explains how to convert primitive types between C and Python.
How to send python dict to C++
you will likely need to include dictobject.h, floatobject.h, , if not already pulled in via other headers. Here is a way to grab all the values from a dict of floating point numbera to a vector. Depending on what's actually in the dict and how that's structured you may want to look at keys and other pieces.
Note that this is C++ and thus should be compiled as such.
//returns true on success
bool dictToVector(PyObject * srcDict, std::vector<double> & destVector) {
destVector.clear();
if(PyDict_Check(srcDict)) {
Py_ssize_t numItems = PyDict_Size(srcDict);
destVector.reserve(numItems);
Py_ssize_t iteratorPPOS = 0;
PyObject * currentVal;
while(PyDict_Next(srcDict, &iteratorPPOS, NULL, ¤tVal) {
// might be worth checking PyFloat_Check...
destVector.push_back(PyFloat_AsDouble(currentVal));
}
return (numItems == destVector.size());
}
else { // not a dict return with failure
return false;
}
}
Your wrapper will be similar at the end in that it will need to copy the result of mmult into the of result type numpy.ndarray.
Usage of the above something like:
PyObject* mmult_wrapper(PyObject * e, PyObject * new_data, PyObject * neighbour_num, PyObject * result) {
int32_t Cresult[16];
std::vector<double> Ce;
bool noErrorSoFar = dictToVector(e,Ce);
if(Ce.size() == 100) {
mmult(PyFloat_AsDouble(new_data) , PyFloat_AsDouble( neighbour_num), Ce.data(), Cresult);
}
else { // not 100 doubles in the data read!
noErrorSoFar = false;
}
... //some stuff to copy Cresult to the python, and return something meaningful?
}
Converting a python dictionary to cpp object
You almost got the syntax correct:
#include <unordered_map>
#include <vector>
std::unordered_map<int, std::vector<int>> G_Calib_VoltageDigits = {
{1024, {1, 2, 3}},
{2048, {4, 5, 6}}
};
Live example
Explanation: a std::map
or a std::unordered_map
contains elements as pair. A space cannot separate initializer arguments. The correct syntax require a set of braces for the pair, and another for the vector.
convert all the values in a dictionary to strings
Try this
list = [{'a':'p', 'b':2, 'c':'k'},
{'a':'e', 'b':'f', 'c':5}]
for dicts in list:
for keys in dicts:
dicts[keys] = str(dicts[keys])
print(list)
How to convert Python dict to the C++ counter part in Pybind11?
OK, I found the issue, before that I ended up doing the conversion like this :
map<std::string, int> convert_dict_to_map(py::dict dictionary)
{
map<std::string, int> result;
for (std::pair<py::handle, py::handle> item : dictionary)
{
auto key = item.first.cast<std::string>();
auto value = item.second.cast<int>();
//cout << key << " : " << value;
result[key] = value;
}
return result;
}
and then, looked carefully at the :
auto cppmap = kwargs.cast<map<int, int>>();
and finally noticed my issue.
it should have been :
auto cppmap = kwargs.cast<map<std::string, int>>();
I made a mistake, when I changed my example dict and later on reverted back the changes but forgot to change the signature!
Anyway, it seems the first solution may be a better choice, as it allows the developer to work with Python
's dynamic nature better.
That is, a Python
dictionary may very well, include different pairs (such as string:string
, string:int
, int:float
, etc all in the same dictionary object). Therefore, making sure the items are validly reconstructed in c++ can be done much better using the first crude method!
Convert a python dict to a string and back
The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.
import json
json.dumps(dict)
How can I write with a translator's dictionary?
dict(input().split(' ') for i in range(tedad))
is not compatible with the inputs you give with not 2 words per line
One way can be from your code :
tedad = int(input())
d = {}
for i in range(tedad):
l = input().split()
for x in l[1:]:
d[x] = l[0]
c = ''
car = input().split()
for x in car:
c += ' ' + (d.get(x) or x)
print(c[1:])
having that in the file p.py and the input in i :
pi@raspberrypi:/tmp $ cat i
4
man I je ich
kheili very très sehr
alaghemand interested intéressé interessiert
barnamenevisi programming laprogrammation Programmierung
I am very interested in programming
pi@raspberrypi:/tmp $ python3 p.py < i
man am kheili alaghemand in barnamenevisi
pi@raspberrypi:/tmp $
How to convert string values from a dictionary, into int/float datatypes?
for sub in the_list:
for key in sub:
sub[key] = int(sub[key])
Gives it a casting as an int instead of as a string.
Related Topics
Why Should I Ever Use Inline Code
How to See the Template Instantiated Code by C++ Compiler
How to Use Sort() in C++ with Custom Sort Member Function
When to Make a Type Non-Movable in C++11
Recommended Values for Opencv Detectmultiscale() Parameters
Opengl Gl_Polygon Concave Polygon Doesn't Color In
Why Is Cuda Pinned Memory So Fast
How to Emulate _Mm256_Loadu_Epi32 with Gcc or Clang
Why Using the Const Keyword Before and After Method or Function Name
C++ Sizeof(Array) Return Twice the Array's Declared Length
Which Stl Container Should I Use for a Fifo
Best Introduction to C++ Template Metaprogramming
Std::Thread Calling Method of Class
Header File Included Only Once in Entire Program