Python3, building nested dictionary
问题 I'm new with Python, coming from Perl where I've used something like this very often: #!/usr/bin/env perl my %d; my $a = 12; $b = 14; $c = 16; $d{$a}{$b}{$c} = 42; print($d{$a}{$b}{$c}); # 42 How can fill a dictionary in python e.g. in a loop If I try this with Python, I've got a KeyError a = 12 b = 14 c = 16 my_dict[a][b][c] = 42 # KeyError Is this the only way? if a in my_dict: if b in my_dict[a]: my_dict[a][b][c] = 42 else: my_dict[a][b] = {} my_dict[a][b][c] = 42 else: my_dict[a] = {} my