LoginSignup
20
21

More than 5 years have passed since last update.

pythonで多次元連想配列を扱う

Last updated at Posted at 2018-07-01

pythonで多次元連想配列を実装する備忘録です。

やりたいこと

例えばPerlだと以下のように簡単にハッシュ(pythonだと辞書)の多次元連想配列ができます。

#!/usr/bin/perl

my %hash = {};
$hash{'a'}{'b'}{'c'} = 'd';
$hash{'e'}{'f'} = 'g';

print $hash{'a'}{'b'}{'c'}, "\n";
print $hash{'e'}{'f'}, "\n";

これをpythonでやろうとすると以下のようにエラーが発生します。

#!/usr/bin/env python3

hash = {}
hash['a']['b']['c'] = 'd'

print(hash)
$ ./example.py
Traceback (most recent call last):
  File "./example.py", line 4, in <module>
    hash['a']['b']['c'] = 'd'
KeyError: 'a'

Perlだと簡単にできるのにpythonだと一手間加えないとできなかったので備忘録として書いておきます。

多次元連想配列のやり方

defaultdict を使ってやるやり方が簡単かと思います。

#!/usr/bin/env python3
from collections import defaultdict

nested_dict = lambda: defaultdict(nested_dict)
hash = nested_dict()

hash['a']['b']['c'] = 'd'
hash['e']['f'] = 'g'

print(hash['a']['b']['c'])
print(hash['e']['f'])

これで、やりたいことが出来ました :)

20
21
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
20
21