[PYTHON] Sorting of multidimensional associative arrays

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

Sorting of multidimensional associative arrays
Multiplication of multidimensional arrays by einsum (Einstein notation)
[Question] About multidimensional arrays
Sum of multiple numpy arrays (sum)
python> Handling of 2D arrays
[Neta] Sorting algorithm of O (1)
Multidimensional array initialization of list
[Python] Copy of multidimensional list
Implementation of original sorting in Python