Python Query properties of dict by value
<p>I'm trying to get the count of properties in a dict where poi == true. I've included a C# example for reference, followed by my python code. </p>

<p>What's the correct way of doing this in Python?</p>

<p>C#:</p>

<pre><code>enron_data.where(x =&gt; x.poi == true).count()
</code></pre>

<p>In Python:</p>

<pre><code>i = 0
for key,value in enron_data.items():
    if value["poi"]:
        i = i + 1
print i
</code></pre>

<p>enron_data Sample:</p>

<pre><code>{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', 'total_payments': 1061827, 'exercised_stock_options': 'NaN', 'bonus': 600000, 'restricted_stock': 585062, 'shared_receipt_with_poi': 702, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 585062, 'expenses': 94299, 'loan_advances': 'NaN', 'from_messages': 29, 'other': 1740, 'from_this_person_to_poi': 1, 'poi': False, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 'NaN', 'email_address': 'mark.metts@enron.com', 'from_poi_to_this_person': 38}}
</code></pre>

<p>I'd probably do something like this assuming that the <code>poi</code> is always <code>True</code> or <code>False</code>. </p>

<pre><code>sum(int(v['poi']) for v in enron_data.values())
</code></pre>

<p><code>enron_data.values()</code> gives you an iterator that will return values of the dictionary. We're not interested in the keys. For each one, we get the value of the <code>'poi'</code> key. That's what </p>

<pre><code>[v['poi'] for v in enron_data.values()]
</code></pre>

<p>will give you. Assuming that <code>v['poi']</code> is always <code>True</code> or <code>False</code>, I convert it to an integer using <code>int()</code>. <code>int(True)</code> is <code>1</code> and <code>int(False)</code> is <code>0</code>. So, if I run this, I will get a list of <code>1</code>s and <code>0</code>s. Then I <code>sum</code> the entire list to get the count of <code>1</code>s (i.e. <code>True</code>s) using the <code>sum</code> builtin. I drop the <code>[</code> and <code>]</code> because I'm just going to iterate over the list and not index it or anything.</p>

<p>Here's another alternative that occurred to me.</p>

<pre><code>sum(1 for v in enron_data.values() if v['poi'] is True)
</code></pre>

python