Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You cannot sort a <code>dict</code> because dictionary has no ordering. </p> <p>Instead, use <a href="http://docs.python.org/library/collections.html#collections.OrderedDict" rel="noreferrer"><code>collections.OrderedDict</code></a>:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; d = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3} &gt;&gt;&gt; od = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True)) &gt;&gt;&gt; od OrderedDict([('Gears of war 3', 6), ('Batman', 5), ('gears of war 3', 4), ('Rocksmith', 5), ('Madden', 3)]) &gt;&gt;&gt; od.keys() ['Gears of war 3', 'Batman', 'gears of war 3', 'Rocksmith', 'Madden'] &gt;&gt;&gt; od.values() [6, 5, 4, 5, 3] &gt;&gt;&gt; od['Batman'] 5 </code></pre> <hr> <p>The "order" you see in an JSON object is not meaningful, as JSON object is unordered[<a href="http://www.ietf.org/rfc/rfc4267.txt" rel="noreferrer">RFC4267</a>]. </p> <p>If you want meaningful ordering in your JSON, you need to use a list (that's sorted the way you wanted). Something like this is what you'd want:</p> <pre><code>{ "count": 24, "top 5": [ {"Gears of war 3": 6}, {"Batman": 5}, {"Rocksmith": 5}, {"gears of war 3": 4}, {"Madden": 3} ] } </code></pre> <p>Given the same dict <code>d</code>, you can generate a sorted list (which is what you want) by:</p> <pre><code>&gt;&gt;&gt; l = sorted(d.items(), key=lambda x:x[1], reverse=True) &gt;&gt;&gt; l [('Gears of war 3', 6), ('Batman', 5), ('Rocksmith', 5), ('gears of war 3', 4), ('Madden', 3)] </code></pre> <p>Now you just pass <code>l</code> to <code>m['top5']</code> and dump it:</p> <pre><code>m["Top 5"]= l k = json.dumps(m) </code></pre>
    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. 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