problem with sorting

A

ankitks.mital

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

now if I wanted sorted values in list, i am not able to do thisNone

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

Paddy

{'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.
 
J

jwelby

{'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.
[0, 2, 3]

or you can use sorted(), which does return the sorted sequence:
[0, 2, 3]
 
R

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
 
C

castironpi

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() ).

Can it return the right things from the right things in order from the
givens? ( dvals , values, sort, print ).decode()
 
D

Duncan Booth

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.
 
B

bearophileHUGS

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top