472,331 Members | 1,740 Online

# Sort a Dictionary

This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php
Jul 18 '05 #1
9 16557
Afanasiy:
This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys

for k in ksort(d):
print k, v

As a bonus, you don't need to tell the sort to sort numerically
vs. lexigraphically --- Python's strong typing knows that by
default. You can pass in an alternate compare function if you
want.

And no, I haven't tested it. ;)

Andrew
da***@dalkescientific.com
Jul 18 '05 #2
Afanasiy:
This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys

for k in ksort(d):
print k, v

As a bonus, you don't need to tell the sort to sort numerically
vs. lexigraphically --- Python's strong typing knows that by
default. You can pass in an alternate compare function if you
want.

And no, I haven't tested it. ;)

Andrew
da***@dalkescientific.com
Jul 18 '05 #3
On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <ad****@mindspring.com>
wrote:
Afanasiy:
This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys

for k in ksort(d):
print k, v

As a bonus, you don't need to tell the sort to sort numerically
vs. lexigraphically --- Python's strong typing knows that by
default. You can pass in an alternate compare function if you
want.

Why wouldn't this be a standard function?
Jul 18 '05 #4
On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <ad****@mindspring.com>
wrote:
Afanasiy:
This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys

for k in ksort(d):
print k, v

As a bonus, you don't need to tell the sort to sort numerically
vs. lexigraphically --- Python's strong typing knows that by
default. You can pass in an alternate compare function if you
want.

Why wouldn't this be a standard function?
Jul 18 '05 #5
On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <ad****@mindspring.com>
wrote:
Afanasiy:
This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys

for k in ksort(d):
print k, v

http://www.php.net/manual/en/function.asort.php
Jul 18 '05 #6
On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <ad****@mindspring.com>
wrote:
Afanasiy:
This is fairly simple in PHP, how do I do it in Python?

http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
keys = d.keys()
keys.sort(func)
return keys

for k in ksort(d):
print k, v

http://www.php.net/manual/en/function.asort.php
Jul 18 '05 #7
Afanasiy:
Why wouldn't [ksort] be a standard function?
Because it isn't needed all that often and can be built (when needed)
from the underlying primitives very simply. Because if there are a
lot of similar methods then it becomes harder to remember what each
one does.

The normal practice is

keys = d.keys()
keys.sort()
for k in keys:
....

which isn't all that onerous.

http://www.php.net/manual/en/function.asort.php

The normal idiom for sorting by value then printing
the key/value pairs is

rev_items = [(v, k) for k, v in d.items()]
rev_items.sort()
for v, k in rev_items:
print k, v

If you want that as a function return just the keys
in value order

def asort(d):
rev_items = [(v, k) for k, v in d.items()]
rev_items.sort()
return [k for (v, k) in rev_items]

As you can see, there are many ways you might want
to sort a dict. Why should all of them be present in
the standard dict type when it's really a matter of two
extra lines to get what you need. Seeing the code in
this case is much easier than memorizing the 7 different
sort functions mentioned in the PHP docs.

Additionally, Python's keys can be more complex than
a string or int. Eg,

d = {}
d[ (0,0) ] = "home"
d[ (1,3) ] = "school"
d[ (4,2) ] = "work"

y_items = [(y, name) for ((x, y), name) in d.items()]
y_items.sort()
for y, name in y_items:
print y, name

sorts by y position, ignoring x position. PHP doesn't
have a function for that, but it follows pretty naturally
from the idiomatically Python way to do it.

Andrew
da***@dalkescientific.com
Jul 18 '05 #8
Afanasiy:
Why wouldn't [ksort] be a standard function?
Because it isn't needed all that often and can be built (when needed)
from the underlying primitives very simply. Because if there are a
lot of similar methods then it becomes harder to remember what each
one does.

The normal practice is

keys = d.keys()
keys.sort()
for k in keys:
....

which isn't all that onerous.

http://www.php.net/manual/en/function.asort.php

The normal idiom for sorting by value then printing
the key/value pairs is

rev_items = [(v, k) for k, v in d.items()]
rev_items.sort()
for v, k in rev_items:
print k, v

If you want that as a function return just the keys
in value order

def asort(d):
rev_items = [(v, k) for k, v in d.items()]
rev_items.sort()
return [k for (v, k) in rev_items]

As you can see, there are many ways you might want
to sort a dict. Why should all of them be present in
the standard dict type when it's really a matter of two
extra lines to get what you need. Seeing the code in
this case is much easier than memorizing the 7 different
sort functions mentioned in the PHP docs.

Additionally, Python's keys can be more complex than
a string or int. Eg,

d = {}
d[ (0,0) ] = "home"
d[ (1,3) ] = "school"
d[ (4,2) ] = "work"

y_items = [(y, name) for ((x, y), name) in d.items()]
y_items.sort()
for y, name in y_items:
print y, name

sorts by y position, ignoring x position. PHP doesn't
have a function for that, but it follows pretty naturally
from the idiomatically Python way to do it.

Andrew
da***@dalkescientific.com
Jul 18 '05 #9
On Sat, Aug 23, 2003 at 02:03:09AM +0000, Afanasiy wrote:
This is fairly simple in PHP, how do I do it in Python?

In PHP, associative arrays are still regular arrays too, you can access
them by index (IIRC), and when you loop through them, they maintain the
order in which you assigned their items. Python seperates associative
arrays (dicts/hashes) from numerically indexed arrays (lists). You
can't sort a dict, because a dict has no order. You could do something
like:

mydict = { ..whatever.. }

sortedkeys = mydict.keys()
sortedkeys.sort()

for key in sortedkeys:
print key, mydict[key]

Then we run into the issue of why we have to do list.sort() in place,
and I'm sure that's been discussed here a billion times (can't say I've
been part of any of those discussions though).

--
m a c k s t a n n mack @ incise.org http://incise.org
After a few boring years, socially meaningful rock 'n' roll died out.
It was replaced by disco, which offers no guidance to any form of life
more advanced than the lichen family.
-- Dave Barry, "Kids Today: They Don't Know Dum Diddly Do"

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

### Similar topics

 15 by: KraftDiner | last post by: I have two lists. I want to sort by a value in the first list and have the second list sorted as well... Any suggestions on how I should/could do... 99 by: Shi Mu | last post by: Got confused by the following code: >>> a >>> b >>> c {1: , ], 2: ]} >>> c.append(b.sort()) >>> c {1: , ], 2: , None]} 4 by: Markus Franz | last post by: Hi! I have: x = {'a':3, 'b':2, 'c':4} How can I sort x by value? (I tried using sorted() with x.items() - but I didn't get a dictionary as... 6 by: max sharma | last post by: Hi all, I am using a hashtable for my application. Its similar to word count application. How can I sort the hashtable w.r.t. the VALUE and not... 8 by: spohle | last post by: hi i have a normal dictionary with key and value pairs. now i wanna sort by the keys BUT in a specific order i determine in a list !? any ideas ... 5 by: Neil Chambers | last post by: Hi All, I'm looking to see if it's feasible to use the SortObjectCommand included in the Microsoft.Powershell.Commands assembly. I have a... 2 by: kdt | last post by: Hi, I need to perform some horrible functions in python I need to do, using sort in a similar way that Excel can. With a dictionary like: ... 1 by: pravinasp | last post by: Hello there Iam stuck trying to sort the dictionary object in classic asp. Am trying to sort by the values of the dictionary object and not using... 4 by: NvrBst | last post by: I have a log viewer. I sort the DataGridView by the Time Column and then run a function to set all cell backcolors depending if the cell above is... 0 by: tammygombez | last post by: Hey fellow JavaFX developers, I'm currently working on a project that involves using a ComboBox in JavaFX, and I've run into a bit of an issue.... 0 by: teenabhardwaj | last post by: How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of... 0 by: CD Tom | last post by: This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right... 0 by: CD Tom | last post by: This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins... 0 by: jalbright99669 | last post by: Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made... 0 by: antdb | last post by: Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was... 0 by: Matthew3360 | last post by: Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ... 2 by: Matthew3360 | last post by: Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it... 0 by: AndyPSV | last post by: HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...