问题
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_dict[a][b] = {}
my_dict[a][b][c] = 42
回答1:
You may use dict.setdefault(key, default_value)
my_dict = {}
my_dict.setdefault(a, {}).setdefault(b, {}).setdefault(c, 42)
print(my_dict) # {12: {14: {16: 42}}}
my_dict = {a: {}}
my_dict.setdefault(a, {}).setdefault(b, {}).setdefault(c, 42)
print(my_dict) # {12: {14: {16: 42}}}
my_dict = {a: {b: {}}}
my_dict.setdefault(a, {}).setdefault(b, {}).setdefault(c, 42)
print(my_dict) # {12: {14: {16: 42}}}
回答2:
it is actually better to use deafaultdict instead for this specific use case (it is a nested default dict inspired from this answer):
from collections import defaultdict
def nested_dict():
return defaultdict(nested_dict)
my_dict = defaultdict(nested_dict)
a = 12
b = 14
c = 16
my_dict[a][b][c] = 42 # no KeyError
my_dict[a][b][c]
>>> 42
来源:https://stackoverflow.com/questions/65529456/python3-building-nested-dictionary