Using SortedDictionary for .net (imported from C# .dll)
<p>I'm currently working on a python (for .NET) project that interacts with a C# .dll. However, something is wrong with the SortedDictionary I'm importing.</p>

<p>This is what I'm doing:</p>

<pre><code>import clr
from System.Collections.Generic import SortedDictionary
sorted_dict = SortedDictionary&lt;int, bool&gt;(1, True)
</code></pre>

<p>I get the following error when calling Count on sorted_dict:</p>

<pre><code>AttributeError: 'tuple' object has no attribute 'Count'
</code></pre>

<p>sorted_dict doesn't allow me to call any of the public member functions I see in the interface (Add, Clear, ContainsKey, etc.). Am I doing this correctly?</p>

<p>The problem is this:</p>

<pre><code>SortedDictionary&lt;int, bool&gt;(1, True)
</code></pre>

<p>The <code>&lt;</code> and <code>&gt;</code> symbols in this line are being taken as <em>comparison operators.</em> Python sees you asking for two things:</p>

<pre><code> SortedDictionary &lt; int
 bool &gt; (1, True)
</code></pre>

<p>The comma between these expressions makes the results into a tuple, so you get <code>(True, True)</code> as a result. (Python 2.x lets you compare anything; the result may not have any reasonable meaning, as is the case here.)</p>

<p>Clearly, Python does not use the same <code>&lt;...&gt;</code> syntax as C# for generic types. Instead, you use <code>[...]</code>:</p>

<pre><code>sorted_dict = SortedDictionary[int, bool](1, True)
</code></pre>

<p>This still doesn't work: you get:</p>

<pre><code>TypeError: expected IDictionary[int, bool], got int
</code></pre>

<p>This is because you are trying to instantiate the class with two parameters, when it wants a single parameter that has a dictionary interface. So this will work:</p>

<pre><code>sorted_dict = SortedDictionary[int, bool]({1: True})
</code></pre>

<p>Edit: I originally assumed you were using IronPython. Looks like Python for .NET uses a similar approach, so I believe the above should still work.</p>

python .net