Append to a list of dictionaries in python
<pre><code>self.LOG_DIR_LIST_BACKEND = [AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG]
backend_nodes = [backend-1, backend-2, backend-3]

self.log_in_nodes = []
log_file = {}
for LOG_DIR_BACKEND in self.LOG_DIR_LIST_BACKEND:
    for node_backend in backend_nodes:
        log_in_nodes 'find %s -type f -name \"*log.*.gz\"' % LOG_DIR_BACKEND
        log_file[node_backend] = log_in_nodes
        self.log_in_nodes.append(log_file)
    print "Logs are ", self.log_in_nodes
</code></pre>

<p>Expected output : </p>

<pre><code>[{backend-1: AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG, backend-2: AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG, backend-3: AMPLI_LOG, VAR_LOG, CORE_DUMP_LOG}] 
</code></pre>

<p>When I print self.log_in_nodes, the output is everytime new, it is not appending. What am i doing wrong?</p>

<p>Every time you run this method, it will reset <code>self.log_in_nodes</code>, because you are doing:</p>

<pre><code>self.log_in_nodes = []
</code></pre>

<p>If you want to append stuff to that list, either make this like a class variable or put it outside the class, and initialize only once.</p>

<p>Option one:</p>

<pre><code> class Foo
     log_in_nodes = []

 def your_method(self ...):
     log_file = {}
     for LOG_DIR_BACKEND in self.LOG_DIR_LIST_BACKEND:
         for node_backend in backend_nodes:
             ....
             self.log_in_nodes.append(log_file)
</code></pre>

<p>Option 2: 
     LOG_IN_NODES = []</p>

<pre><code> class Foo

 def your_method(self ...):
     log_file = {}
     for LOG_DIR_BACKEND in self.LOG_DIR_LIST_BACKEND:
         for node_backend in backend_nodes:
             ....
             LOG_IN_NODES.append(log_file)
</code></pre>

<p>In both cases the list is initialized once, and appended every time you call the method.</p>

<h3>side notes:</h3>

<p>What is this: </p>

<pre><code>log_in_nodes 'find %s -type f -name \"*log.*.gz\"' % LOG_DIR_BACKEND`
^^^^^^^^^^^^  Did you miss type this?   forget an assignment?
</code></pre>

<p>probably you meant:</p>

<pre><code>log_in_nodes = 'find %s -type f -name \"*log.*.gz\"' % LOG_DIR_BACKEND
</code></pre>

<p>Instead of:</p>

<pre><code>backend_nodes = [backend-1, backend-2, backend-3]
</code></pre>

<p>You can do:</p>

<pre><code>backend_nodes = range(backend - 1, backend - 4, -1)
</code></pre>

<p>although not really shorter, it is immediately clear what it is doing, compared to the way you wrote the code.</p>

python