简体   繁体   中英

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.

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.

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.

Thanks

You can use a defaultdict and set the default value to a new defaultdict . https://docs.python.org/3/library/collections.html#collections.defaultdict

Related question: Multiple levels of 'collection.defaultdict' in Python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM