By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,077 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

problem with sorting

P: n/a
>>dict = {'M':3, 'R':0, 'S':2}
>>print dict
{'S': 2, 'R': 0, 'M': 3}

now if I wanted sorted values in list, i am not able to do this
>>print dict.values().sort()
None

it returns None instead of [0, 2, 3]

Mar 28 '08 #1
Share this Question
Share on Google+
5 Replies


P: n/a
On Mar 28, 5:38 am, ankitks.mi...@gmail.com wrote:
>dict = {'M':3, 'R':0, 'S':2}
print dict

{'S': 2, 'R': 0, 'M': 3}

now if I wanted sorted values in list, i am not able to do this>>print dict.values().sort()

None

it returns None instead of [0, 2, 3]
Try:

from pprint import pprint as pp
pp(my_dict)
It works well for other built-in types too.

P.S it is not good to use a name, dict, that already has a use in
Python.

- Paddy.
Mar 28 '08 #2

P: n/a
On Mar 28, 5:38 am, ankitks.mi...@gmail.com wrote:
>dict = {'M':3, 'R':0, 'S':2}
print dict

{'S': 2, 'R': 0, 'M': 3}

now if I wanted sorted values in list, i am not able to do this>>print dict.values().sort()

None

it returns None instead of [0, 2, 3]
The sort method works by sorting 'in place'. That means it doesn't
return the sorted value, but just sorts the sequence.
>>t = {'M':3, 'R':0, 'S':2}
x = t.values()
x.sort()
x
[0, 2, 3]

or you can use sorted(), which does return the sorted sequence:
>>sorted(t.values())
[0, 2, 3]
Mar 28 '08 #3

P: n/a
raj
To ankit:

Well, sort() doesn't return the sorted list. It returns None. Why not
this straightforward way?
dvals = dict.values()
dvals.sort()
print dvals
Mar 28 '08 #4

P: n/a
ca********@gmail.com wrote:
On Mar 28, 1:57˙am, raj <rajeeshrn...@gmail.comwrote:
>To ankit:

Well, sort() doesn't return the sorted list. It returns None. Why not
this straightforward way?
dvals = dict.values()
dvals.sort()
print dvals

Why not sorted( dict.values() ).
If you are going to do it that way then it may be preferable to use
itervalues:

print sorted(dict.itervalues())

Both this and raj's suggestion create a single sorted list. Your suggestion
creates two lists: the unsorted one and a separate sorted one. In most
cases the difference is probably insignificant, but if you have a *lot* of
values it might make a difference.
Mar 28 '08 #5

P: n/a
Duncan Booth:
Both this and raj's suggestion create a single sorted list. Your suggestion
creates two lists: the unsorted one and a separate sorted one. In most
cases the difference is probably insignificant, but if you have a *lot* of
values it might make a difference.
The good thing of Python 3.0 is that it forces you to do the right
thing here :-)

Bye,
bearophile
Mar 28 '08 #6

This discussion thread is closed

Replies have been disabled for this discussion.