3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

多次元連想配列のソート

Last updated at Posted at 2021-01-01

Pythonで少し複雑な辞書オブジェクトをsortする - 午後から→オーバークロック
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'
        };
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?