简体   繁体   中英

Translate C++ map to python dictionary

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?

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

像这样吗

dpt2[key_t] = dpt2.get(key_t, 0) + rat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM