Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Personally, one of the things I love about python is the tuple-dict combination. What you have here is effectively a 2d array (where x = fruit name and y = color), and I am generally a supporter of the dict of tuples for implementing 2d arrays, at least when something like <code>numpy</code> or a database isn't more appropriate. So in short, I think you've got a good approach.</p> <p>Note that you can't use dicts as keys in a dict without doing some extra work, so that's not a very good solution. </p> <p>That said, you should also consider <a href="http://docs.python.org/dev/library/collections.html#collections.namedtuple" rel="noreferrer">namedtuple()</a>. That way you could do this:</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Fruit = namedtuple("Fruit", ["name", "color"]) &gt;&gt;&gt; f = Fruit(name="banana", color="red") &gt;&gt;&gt; print f Fruit(name='banana', color='red') &gt;&gt;&gt; f.name 'banana' &gt;&gt;&gt; f.color 'red' </code></pre> <p>Now you can use your fruitcount dict:</p> <pre><code>&gt;&gt;&gt; fruitcount = {Fruit("banana", "red"):5} &gt;&gt;&gt; fruitcount[f] 5 </code></pre> <p>Other tricks:</p> <pre><code>&gt;&gt;&gt; fruits = fruitcount.keys() &gt;&gt;&gt; fruits.sort() &gt;&gt;&gt; print fruits [Fruit(name='apple', color='green'), Fruit(name='apple', color='red'), Fruit(name='banana', color='blue'), Fruit(name='strawberry', color='blue')] &gt;&gt;&gt; fruits.sort(key=lambda x:x.color) &gt;&gt;&gt; print fruits [Fruit(name='banana', color='blue'), Fruit(name='strawberry', color='blue'), Fruit(name='apple', color='green'), Fruit(name='apple', color='red')] </code></pre> <p>Echoing chmullig, to get a list of all colors of one fruit, you would have to filter the keys, i.e. </p> <pre><code>bananas = [fruit for fruit in fruits if fruit.name=='banana'] </code></pre>
 

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