Mutators

Nov 08, 2007 14:06

Let us consider the following code to loop over the keys from a dictionary in Python:

for key in a_dict.keys():This would be nearly the same in Perl:

for my $key in (keys %a_dict) {And Perl 6*:

for %a_dict.k -> my $key {But now you say: I want to have in a sorted rather then arbitrary order ( Read more... )

perl, python, programming

Leave a comment

Comments 4

radiotelescope November 23 2007, 17:16:20 UTC
Very belated:

for val in sorted(dic.keys()): ...

or even

for val in sorted(dic): ...

Reply

radiotelescope November 23 2007, 17:21:07 UTC
(That's Python 2.4.)

Reply

daerr November 26 2007, 18:53:15 UTC
Yeah, I'd been meaning to to post something about this having learned about sorted() after having posted. Didn't know about the non-keys form... is val a pair in that case? (Is a pair a concept in python?)

Reply


radiotelescope November 28 2007, 18:17:33 UTC
Python has pairs, but "for key in dic" iterates through the keys. To iterate through pairs, you'd say "for pair in dic.items()". Or, more likely, "for (key, val) in dic.items()".

"sorted(dic.items())" is legal, because it sorts pairs by the first column and then the second column.

Reply


Leave a comment

Up