473,386 Members | 1,757 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,386 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 16750
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

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.