Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Edit</strong> -- warning: the following works only for this <em>specific</em> case, <strong>not</strong> for the general case -- see below.</p> <pre><code>int value = 0; d.TryGetValue(p, out value); d[p] = value + 1; </code></pre> <p>this is equivalent to the following Python snippet (which is better than the one you show):</p> <pre><code>d[p] = d.get(p, 0) + 1 </code></pre> <p><code>setdefault</code> is like <code>get</code> (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 <code>d[p]</code> anyway, so using <code>setdefault</code> in this case is just goofy (complicates things and slow you down to no good purpose).</p> <p>In C#, <code>TryGetValue</code>, as the name suggests, tries to get the value corresponding to the key into its <code>out</code> parameter, but, if the key's not present, then it (<strong>warning: the following phrase is <em>not</em> correct:</strong>) just leaves said value alone (<strong>edit:</strong>) What it actually does if the key's not present is <em>not</em> to "leave the value alone" (it can't, since it's an <code>out</code> 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 <code>TryGetValue</code> a general-purpose substitute for Python's <code>dict.get</code>.</p> <p><code>TryGetValue</code> 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 <code>dict.get</code>, you need another idiom:</p> <pre><code>if (!TryGetValue(d, k)) { k = whatyouwant; } </code></pre> <p>Now <em>this</em> idiom is indeed the general-purpose equivalent to Python's <code>k = d.get(k, whatyouwant)</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload