Sort a little complicated dictionary object in Python -From the afternoon → Overclock Basic Perl sort -Qiita
Python
s.py
dict = {
1: {
'name': 'A',
'age': 30,
},
2: {
'name': 'B',
'age': 31,
},
3: {
'name': 'C',
'age': 29,
},
}
for i in sorted(dict.items(), key=lambda x: x[1]['age'], reverse=True):
print(i)
$ python3 s.py
(2, {'name': 'B', 'age': 31})
(1, {'name': 'A', 'age': 30})
(3, {'name': 'C', 'age': 29})
Perl
s.pl
use strict;
use warnings;
use Data::Dumper;
my %hash = (
1 => { name => 'A', age => 30 },
2 => { name => 'B', age => 31 },
3 => { name => 'C', age => 29 },
);
foreach my $key ( reverse sort { $hash{$a}{'age'} <=> $hash{$b}{'age'} } keys %hash ){
print "$key\n";
print Dumper \%{$hash{$key}};
}
$ perl p.pl
2
$VAR1 = {
'name' => 'B',
'age' => 31
};
1
$VAR1 = {
'age' => 30,
'name' => 'A'
};
3
$VAR1 = {
'age' => 29,
'name' => 'C'
};
Recommended Posts