473,326 Members | 2,124 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

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 16739
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


How about this one?

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


How about this one?

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.
How about this one?

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.
How about this one?

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 this?
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 response.) My second question:
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 the KEY. The sample data of the table is given below...
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 dic = {'key1':'value1', 'key2':'value2',...
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 Dictionary Dictionary<string, intd = new...
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: >>> d {8: (99, 99), 9: , 4: , 5: (67, 77)} I...
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 keys, and once sorted by values i need the keys...
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 different. This works correctly, however, when...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.