Python3, building nested dictionary

一曲冷凌霜 提交于 2021-01-29 17:37:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!