[英]Defining Multi-Dimension Dictionary Dynamically
Im trying to declare a multi dimension dictionary and I find it tedious to always having to create a variable with my inner dict to then assign it to its parent value dict 我试图声明一个多维字典,我发现总是不得不用我的内部字典创建一个变量然后将其分配给它的父值字典很麻烦。
Coming from PHP Im now wondering if im simply missing something. 来自PHP,我现在想知道我是否只是缺少一些东西。
Here is what I mean 这就是我的意思
I used to do this alot 我以前经常这样做
$var['nicolas']['age'] = 25;
$var['nicolas']['isMale'] = True;
$var['some_one_else']['age'] = 30;
$var['some_one_else']['isMale'] = False
I really enjoyed this because it allows me to create loops and dynamically add new key/values. 我真的很喜欢它,因为它允许我创建循环并动态添加新的键/值。
For example 例如
$team_members = array(
"someDepartment" => array(
"Nicolas" => array(
'Title' => 'ConfusedProgrammer',
'Age' => 25,
'Sex' => 'm'
)
),
"OtherDepartment" => array(
"otherGuy" => array(
'Title' => 'Manager',
'Age' => 30,
'Sex' => 'f'
)
)
);
$response = array();
foreach($team_members as $deptName => $deptVal){
foreach($deptVal as $cName => $cVal){
$response[$cName]['Age'] = $cVal['Age'];
$response[$cName]['isMale'] = (strtolower($cVal['Sex']) == 'm'?True:False);
}
}
In python the way I would achieve that would be something similar to the following. 在python中,我将实现的方式类似于以下内容。
parent_dict = {}
parent_dict['test'] = {}
parent_dict['test']['hello'] = 'It works'
parent_dict['test2']['other_way_to_say_hello'] = 'Does not work :( '
What Im trying to do, is avoid having to declare the new dimension. 我想做的是避免声明新尺寸。
Now after researching about this, I realize that the behavior I'm looking for might not be possible at all. 现在,在对此进行研究之后,我意识到我所寻找的行为可能根本不可能。
but was hopping to see how you guys deal with those type of situation. 但希望能看到你们如何处理这种情况。
I am very new to python and to date enjoy it a lot, But I feel like dealing with this type of problem often and does slow my progress down significantly. 我是python的新手,到目前为止很喜欢它,但是我感觉经常要处理这种类型的问题,并且确实大大降低了我的进度。
Thanks 谢谢
You can use a defaultdict
and set the default value to a new defaultdict
. 您可以使用defaultdict
并将默认值设置为新的defaultdict
。 https://docs.python.org/3/library/collections.html#collections.defaultdict https://docs.python.org/3/library/collections.html#collections.defaultdict
Related question: Multiple levels of 'collection.defaultdict' in Python 相关问题: Python中的“ collection.defaultdict”的多个级别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.