gpt4 book ai didi

python - 如何定义嵌套字典

转载 作者:太空宇宙 更新时间:2023-11-03 20:08:06 26 4
gpt4 key购买 nike

我必须使用嵌套字典。我是perl用户...所以python对我来说很难。但我开始学习Python。当我用 perl 和 python 编写如下代码时。 perl 运行良好,但 python 则不然。Python 是管理许多数据树的良好语言。那么你能帮我如何控制这种数据树吗?我只知道 perl 风格..

perl

## working well
$data{apple}{tree}{red}{small}{cheap} = 2;
$data{banana}{tree}{yellow}{big}{cheap} = 3;
$data{grape}{tree}{pupple}{small}{expensive} = 1;
$data{orange}{tree}{orange}{small}{cheap} = 5;

foreach fruite ( sort keys %data) {
foreach source ( sort keys %{$data{$fruite}}){
print "$fruite $source\n";
}
}

python

 data = { }
data['apple']['tree']['red']['small']['cheap'] = 2
# not working well..

#ERROR message in python:
#Traceback (most recent call last):
# File "text_parsing.py", line 97, in <module>
# data['apple']['tree']['red']['small']['cheap'] = 2
#KeyError: 'apple'

最佳答案

使用dict.setdefault

例如:

data = {}
data.setdefault('apple', {}).setdefault('tree', {}).setdefault('red', {}).setdefault('small', {}).setdefault('cheap', 2)
print(data)
# --> {'apple': {'tree': {'red': {'small': {'cheap': 2}}}}}

关于python - 如何定义嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58853075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com