473,372 Members | 1,606 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,372 software developers and data experts.

Sorting dict keys

Consider the following:
>>a = {1:2, 3:4, 2:5}
Say that i want to get the keys of a, sorted. First thing I tried:
>>b = a.keys().sort()
print b
None

Doesn't work. Probably because I am actually trying to sort the keys
of the dictionary without copying them first. If that is the case,
fine. Next thing I do:
>>b = a.keys()
b.sort()
[1, 2, 3]

Works fine, but I would really like it if I could somehow do it in one
line. As the problem seems to be copying the object, i try the
following:
>>import copy
b = copy.copy(a.keys()).sort()
print b
None

Hmmm, why doesn't it work? Also,
>>b = copy.deepcopy(a.keys()).sort()
print b
None

(not that I thought that deepcopy will work since shallow didn't, I
understand the difference :) )
Obviously, I am missing something here. What am I thinking wrong? Why
doesn't copying the object work?
Thanks for all the help

Jul 20 '07 #1
9 3321
mo*********@gmail.com wrote:
Consider the following:
>>>a = {1:2, 3:4, 2:5}

Say that i want to get the keys of a, sorted. First thing I tried:
>>>b = a.keys().sort()
print b
None

Doesn't work. Probably because I am actually trying to sort the keys
of the dictionary without copying them first. If that is the case,
fine.
..sort returns None.
>>>b = a.keys()
b.sort()
[1, 2, 3]
This snippet is clearly edited, because .sort returns None:
>>a = {1:2, 3:4, 2:5}
b = a.keys()
b.sort()
b
[1, 2, 3]

The problem you're having here is that .sort returns None to indicate
that it mutates the object, rather than returning a new one. So get the
keys, sort them, and then move along.
Works fine, but I would really like it if I could somehow do it in one
line.
Why is doing it in one line a priority? Clarity is more important than
brevity.

Regardless, you can do it in one line with the sorted builtin:
>>sorted(a.keys())
[1, 2, 3]

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
We must all hang together, or, most assuredly, we will all hang
separately. -- John Hancock
Jul 20 '07 #2
mo*********@gmail.com wrote:
Consider the following:
>>>>a = {1:2, 3:4, 2:5}


Say that i want to get the keys of a, sorted. First thing I tried:

>>>>b = a.keys().sort()
print b

None

Doesn't work. Probably because I am actually trying to sort the keys
of the dictionary without copying them first. If that is the case,
fine. Next thing I do:

>>>>b = a.keys()
b.sort()

[1, 2, 3]

Works fine, but I would really like it if I could somehow do it in one
line. As the problem seems to be copying the object, i try the
following:

>>>>import copy
b = copy.copy(a.keys()).sort()
print b

None

Hmmm, why doesn't it work? Also,

>>>>b = copy.deepcopy(a.keys()).sort()
print b

None

(not that I thought that deepcopy will work since shallow didn't, I
understand the difference :) )
Obviously, I am missing something here. What am I thinking wrong? Why
doesn't copying the object work?
Thanks for all the help
sort() sorts a list in place and returns None. For a one-liner:
>>a = {1:2, 3:4, 2:5}
b = sorted(a.keys())
b
[1, 2, 3]

Duncan
Jul 20 '07 #3
On Fri, Jul 20, 2007 at 03:27:51PM -0700, mo*********@gmail.com wrote:
Consider the following:
>a = {1:2, 3:4, 2:5}

Say that i want to get the keys of a, sorted. First thing I tried:
>b = a.keys().sort()
print b
None
list's sort() method sorts the list _in_place_:
>>l = ['spam', 'eggs']
help(l.sort)
Help on built-in function sort:

sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) --1, 0, 1

That means that doesn't return a sorted version of the list you're
working with. Instead, it sorts the list itself.

If you want to return a sorted list, use (duh) sorted:
>>sorted(l)
['eggs', 'spam', 'spam']

--

[Will Maier]-----------------[wi*******@ml1.net|http://www.lfod.us/]
Jul 20 '07 #4
On 21 srp, 00:47, Duncan Smith <buzz...@urubu.freeserve.co.ukwrote:
montyphy...@gmail.com wrote:
Consider the following:
>>>a = {1:2, 3:4, 2:5}
Say that i want to get the keys of a, sorted. First thing I tried:
>>>b = a.keys().sort()
print b
None
Doesn't work. Probably because I am actually trying to sort the keys
of the dictionary without copying them first. If that is the case,
fine. Next thing I do:
>>>b = a.keys()
b.sort()
[1, 2, 3]
Works fine, but I would really like it if I could somehow do it in one
line. As the problem seems to be copying the object, i try the
following:
>>>import copy
b = copy.copy(a.keys()).sort()
print b
None
Hmmm, why doesn't it work? Also,
>>>b = copy.deepcopy(a.keys()).sort()
print b
None
(not that I thought that deepcopy will work since shallow didn't, I
understand the difference :) )
Obviously, I am missing something here. What am I thinking wrong? Why
doesn't copying the object work?
Thanks for all the help

sort() sorts a list in place and returns None. For a one-liner:
>a = {1:2, 3:4, 2:5}
b = sorted(a.keys())
b

[1, 2, 3]

Duncan
Thanks, this is what I was looking for. I know that .sort() sorts the
list in-place (the snippet I posted was written in a hurry, not pasted
-- I apologise for that). In fact, this is exactly what puzzles me.
copy.copy returns a new object:
>>copy.copy(a.keys())
[1,2,3]

Then why doesn't copy.copy(a.keys()).sort() work??
Thanks to everyone who replied!

Jul 20 '07 #5
On 20 jul, 19:34, montyphy...@gmail.com wrote:
copy.copy returns a new object:
>copy.copy(a.keys())

[1,2,3]

Then why doesn't copy.copy(a.keys()).sort() work??
It works, but you don't notice it, because you don't save a reference
to the new list.
Try this:

c = copy.copy(a.keys())
c.sort()

--
Roberto Bonvallet

Jul 20 '07 #6
On Fri, 20 Jul 2007 15:27:51 -0700, montyphyton wrote:
>>>b = a.keys()
b.sort()
[1, 2, 3]

Works fine, but I would really like it if I could somehow do it in one
line.
Why? Is the Enter key on your keyboard broken? Is there a global shortage
of newline characters that I haven't been told about? Does your employer
pay you less if you write more lines?

--
Steven.

Jul 21 '07 #7
On 21 srp, 02:31, Steven D'Aprano
<st...@REMOVE.THIS.cybersource.com.auwrote:
On Fri, 20 Jul 2007 15:27:51 -0700, montyphyton wrote:
>>b = a.keys()
b.sort()
[1, 2, 3]
Works fine, but I would really like it if I could somehow do it in one
line.

Why? Is the Enter key on your keyboard broken? Is there a global shortage
of newline characters that I haven't been told about? Does your employer
pay you less if you write more lines?

--
Steven.
I'd like to do it in one line because what I am trying to do is, after
all, a single, simple enough action. I find the suggested
b = sorted(a.keys()) much more readable than breaking it up in two
lines. In the long run, I guess it's a matter of personal taste...
Do I get payed less for more source code? Since I'm a student, I don't
get payed at all, regardless of number of lines :)

Jul 21 '07 #8
mo*********@gmail.com wrote:
I'd like to do it in one line because what I am trying to do is,
after all, a single, simple enough action.
No, it's two actions:

1. You extract a list of keys from the dict
2. you sort it
I find the suggested b = sorted(a.keys()) much more readable than
breaking it up in two lines. In the long run, I guess it's a
matter of personal taste...
Yes. You'll see, at least if you do a third thing with the list it
will start to become less well-readable.

Regards,
Björn

--
BOFH excuse #450:

Terrorists crashed an airplane into the server room, have to
remove /bin/laden. (rm -rf /bin/laden)

Jul 21 '07 #9
>From ESR's "Why python?"

b = a.keys(); b.sort()

Two statements, one line. Doesn't create an incidental copy the way
sorted does but I'm not sure how much you like to jam on one line.

Cheers,
Aaron

Jul 21 '07 #10

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

Similar topics

9
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after...
13
by: Paul | last post by:
Hi all I have a sorting problem, but my experience with Python is rather limited (3 days), so I am running this by the list first. I have a large database of 15GB, consisting of 10^8 entries...
6
by: David Rasmussen | last post by:
If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But...
10
by: Gregory Piñero | last post by:
Hey guys, I thought I'd throw this out there since everyone loves optimization questions (it's true, check out the number of replies to those type of questions!) Right now I have a function...
3
by: aking | last post by:
Dear Python people, im a newbie to python and here...so hello! Im trying to iterate through values in a dictionary so i can find the closest value and then extract the key for that...
12
by: jeremito | last post by:
Please excuse me if this is obvious to others, but I can't figure it out. I am subclassing dict, but want to prevent direct changing of some key/value pairs. For this I thought I should override...
9
by: Wolfgang Draxinger | last post by:
H folks, I got, hmm not really a problem, more a question of elegance: In a current project I have to read in some files in a given directory in chronological order, so that I can concatenate...
3
by: james_027 | last post by:
hi, a_dict = {'name':'apple', 'color':'red', 'texture':'smooth', 'shape':'sphere'} is there any difference between .. for key in a_dict: from
1
by: jim-on-linux | last post by:
On Saturday 14 June 2008 03:15, Beema shafreen wrote: I have used this method to solve similar problems. This is a consept of how to do what you want, but you will have to work a little to...
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...
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...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...

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.