Edit -- warning: the following works only for this specific case, not for the general case -- see below.
int value = 0;
d.TryGetValue(p, out value);
d[p] = value + 1;
this is equivalent to the following Python snippet (which is better than the one you show):
d[p] = d.get(p, 0) + 1
setdefault
is like get
(fetch if present, else use some other value) plus the side effect of injecting the key / other value pair in the dict if the key wasn't present there; but here this side effect is useless, since you're about to assign d[p]
anyway, so using setdefault
in this case is just goofy (complicates things and slow you down to no good purpose).
In C#, TryGetValue
, as the name suggests, tries to get the value corresponding to the key into its out
parameter, but, if the key's not present, then it
(warning: the following phrase is not correct:)
just leaves said value alone
(edit:) What it actually does if the key's not present is not to "leave the value alone" (it can't, since it's an out
value; see the comments), but rather to set it to the default value for the type -- here, since 0 (the default value) is what we want, we're fine, but this doesn't make TryGetValue
a general-purpose substitute for Python's dict.get
.
TryGetValue
also returns a boolean result, telling you whether it did manage to get the value or not, but you don't need it in this case (just because the default behavior happens to suit us). To build the general equivalent of Python's dict.get
, you need another idiom:
if (!TryGetValue(d, k)) {
k = whatyouwant;
}
Now this idiom is indeed the general-purpose equivalent to Python's k = d.get(k, whatyouwant)
.