Let us consider the following code to loop over the keys from a dictionary in Python:
In Python you have to allocate a temporary variable, sort it, then loop over the result:
[Edit] So as many people pointed out to me, this was fixed for Python as of 2.4 (my laptop and work machines all use 2.3) with: for key in sorted(a_dict.keys()): What's more, the .keys() is assumed so you can actually just do for key in a_dict: or for key in sorted(a_dict):
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!In Python you have to allocate a temporary variable, sort it, then loop over the result:
the_keys = a_dict.keys() the_keys.sort() for key in the_keys:Where as Perl takes a functional approach that is, in my opinion, a lot clearer:
for my $key in (sort keys %a_dict) {And Perl 6*: for sort %a_dict.k -> my $key {* I vaguely recall something about the temporary variables used in loops not requiring an explicit "my" but I can't seem to find something saying that explicitly now.[Edit] So as many people pointed out to me, this was fixed for Python as of 2.4 (my laptop and work machines all use 2.3) with: for key in sorted(a_dict.keys()): What's more, the .keys() is assumed so you can actually just do for key in a_dict: or for key in sorted(a_dict):


Comments
for val in sorted(dic.keys()): ...
or even
for val in sorted(dic): ...
"sorted(dic.items())" is legal, because it sorts pairs by the first column and then the second column.