Shandeep Murugasamy
Shandeep Murugasamy

Reputation: 311

Adding items to an existing dictionary using loops in python

I want the output to be in the form:

dic = {size1:file/path1, size2:file/path2}

But what I am getting in individual dictionaries for each combination, like:

{size1:file/path1}
{size2:file/path2, size1:file/path1, ...}

This is the code I came up with, can anyone correct my code.

import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
     sys.stdout = outfile
     for cdir, dir, files in os.walk(r'/Users'):
         for file in files:
             if file.endswith('.py'):
                filename = os.path.join(cdir, file)
                size = os.path.getsize(filename)
                records[size] = filename #records = {size:filename}
                print records             #how do I use dict.update() here?   
     sys.stdout = out

Upvotes: 1

Views: 101

Answers (1)

Xiaotian Pei
Xiaotian Pei

Reputation: 3260

there are two problems in your code. the first is you should put print outside your loop. the second is there may be two files with same size, better to put them in a list.

import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
     sys.stdout = outfile
     for cdir, dir, files in os.walk(r'/Users'):
         for file in files:
             if file.endswith('.py'):
                filename = os.path.join(cdir, file)
                size = os.path.getsize(filename)
                records.setdefault(size, []).append(filename)
     print records  
     sys.stdout = out

Upvotes: 1

Related Questions