Search code examples
pythonfor-loopdictionarynested-loops

Python iterating through directories and updating dictionary


Dictionary "d" consists only of the latest iterated subfolder keys and values when I want to add all folders. I don't get why my dictionary starts updating from empty dictionary after folder changes.

import os
from os.path import join

for (dirname, dirs, files) in os.walk('.'):
    d = dict()
    for filename in files:
        if filename.endswith('.txt') :
            value_thefile = os.path.join(dirname,filename)
            key_size = os.path.getsize(value_thefile)
            d.update({key_size:value_thefile})
print d

Solution

  • The dictionary d keeps getting set to a new empty dict for each iteration of the outer for loop. ie It keeps getting re-initialised to {}:

    for (dirname, dirs, files) in os.walk('.'):
        d = dict()    # this makes d == {} for each iteration of os.walk('.')
        for filename in files:
            ...
    

    Instead, initialise it outside the loops, like this:

    d = dict()    # this makes d == {} only at the start
    for (dirname, dirs, files) in os.walk('.'):
        for filename in files:
            ...  # rest of your code