如何轻松创建多级词典

时间:2015-06-21 15:10:17

标签: python dictionary

我想创建一个嵌套的词典,如下例所示:

rule={}
rule["exports-rule-info-2"]["pathname"] = qtree_name
rule["exports-rule-info-2"]["security-rules"]["security-rule-info"]["read-write"]["exports-hostname-info"]["name"] = security_rules 
rule["exports-rule-info-2"]["security-rules"]["security-rule-info"]["root"]["exports-hostname-info"]["name"] = security_rules
rule["exports-rule-info-2"]["security-rules"]["security-rule-info"]["sec-flavor"]["sec-flavor-info"]["flavor"] = 'sec'

2 个答案:

答案 0 :(得分:1)

您可以使用collections.defaultdict。给defaultdict一些用于初始化缺失值的函数。在您的情况下,请使用defaultdict的递归defaultdict

import collections 
infinitedict = lambda: collections.defaultdict(infinitedict)
rule = infinitedict()

将您的内容放入defaultdict后,结果看起来有点像这样(虽然完全喜欢它,因为defaultdict表示略有不同):

{'exports-rule-info-2': {
    'security-rules': {
        'security-rule-info': {
            'read-write': {'exports-hostname-info': {'name': 'security_rules '}}, 
            'root': {'exports-hostname-info': {'name': 'security_rules'}}, 
            'sec-flavor': {'sec-flavor-info': {'flavor': 'sec'}}}}, 
    'pathname': 'qtree_name'}}

答案 1 :(得分:0)

<?php
$servername = "1.1.1.1:111";
$username = "root";
$password = "root";
$dbname = "sit";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$result = mysqli_query($conn, "SELECT * FROM `calltoaction` ");
$values = mysqli_fetch_array($result);

$calltoaction_title = $_POST['calltoaction_title'];
$calltoaction_content = $_POST['calltoaction_content'];

if(isset($_POST['calltoaction_title'])){

$calltoaction= "UPDATE calltoaction SET calltoaction_title='$calltoaction_title' ,calltoaction_content='$calltoaction_content' WHERE  calltoaction_id='1'";

if (mysqli_query($conn, $calltoaction)) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . mysqli_error($conn);
}   


}

?>

<form id="comment_form" method="post" action="<?php $calltoaction?>" onsubmit="setTimeout(function () { window.location.reload(); }, 10), location.reload(true);">
 <table width="100%" border="0" cellspacing="1" cellpadding="2">



<tr>
<td width="85%">About Us Title</td>
</tr>
<tr>
<td><input class="commentarea" name="calltoaction_title" type="text" id="calltoaction_title"value="<?php echo $values['calltoaction_title']?>"></td>
</tr>
<tr>
<td width="85%" >Testimonial</td>
</tr>
<tr>
<td width="85%" >About Us Content</td>
</tr>
<tr>
<td><pre><textarea class="commentarea" name="calltoaction_content" type="text" id="calltoaction_content" rows= "10" ><?php echo $values['calltoaction_content']?></textarea></pre></td>
</tr>


<tr>  
<td>

<input type="submit" value="Update">
</td>
</tr>
 </table>
</form>

<?php mysqli_close($conn); ?>

真的,在你的问题上付出一些努力......