Reputation: 79
I am trying to translate an if-else statement written in c++ to a corresponding chunk of python code. For a C++ map dpt2, I am attempting to translate:
if (dpt2.find(key_t) == dpt2.end()) { dpt2[key_t] = rat; }
else { dpt2.find(key_t) -> second = dpt2.find(key_t) -> second + rat; }
I'm not super familiar with C++, but my understanding is that the -> operator is equivalent to a method call for a class that is being referenced by a pointer. My question is how do I translate this code into something that can be handled by an OrderedDict() object in python?
Upvotes: 0
Views: 424
Reputation: 302663
First of all, in C++ you'd write that as:
dpt[key_t] += rat;
That will do only one map lookup - as opposed to the code you wrote which does 2 lookups in the case that key_t
isn't in the map and 3 lookups in the case that it is.
And in Python, you'd write it much the same way - assuming you declare dpt
to be the right thing:
dpt = collections.defaultdict(int)
...
dpt[key_t] += rat
Upvotes: 6