From 3937e1f06b2e5b3926c082a1cf656ddcd0419a07 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Thu, 17 Sep 2009 18:08:20 -0400 Subject: [PATCH] split final dictionary comprehension example into two steps to make the progression more clear and to avoid calling os.stat twice on each file --- comprehensions.html | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/comprehensions.html b/comprehensions.html index 8d6ba60..747e518 100644 --- a/comprehensions.html +++ b/comprehensions.html @@ -293,14 +293,16 @@ body{counter-reset:h1 3}
 >>> import os, glob, humansize
->>> humansize_dict = {os.path.splitext(f)[0]:humansize.approximate_size(os.stat(f).st_size) \     
-...                   for f in glob.glob('*') if os.stat(f).st_size > 6000}                     
->>> list(humansize_dict.keys())                                                                 
+>>> metadata_dict = {f:os.stat(f) for f in glob.glob('*')}                                  
+>>> humansize_dict = {os.path.splitext(f)[0]:humansize.approximate_size(meta.st_size) \     
+...                   for f, meta in metadata_dict.items() if meta.st_size > 6000}          
+>>> list(humansize_dict.keys())                                                             
 ['romantest9', 'romantest8', 'romantest7', 'romantest6', 'romantest10', 'pluraltest6']
->>> humansize_dict['romantest9']                                                                
+>>> humansize_dict['romantest9']                                                            
 '6.5 KiB'
    -
  1. This dictionary comprehension constructs a list of all the files in the current working directory (glob.glob('*')), filters that list to include only those files larger than 6000 bytes (if os.stat(f).st_size > 6000), and uses that filtered list to construct a dictionary whose keys are the filename minus the extension (os.path.splitext(f)[0]) and whose values are the approximate size of each file (humansize.approximate_size(os.stat(f).st_size)). +
  2. This dictionary comprehension constructs a list of all the files in the current working directory (glob.glob('*')), gets the file metadata for each file (os.stat(f)), and constructs a dictionary whose keys are filenames and whose values are the metadata for each file. +
  3. This dictionary comprehension builds on the previous comprehension, filters out files smaller than 6000 bytes (if meta.st_size > 6000), and uses that filtered list to construct a dictionary whose keys are the filename minus the extension (os.path.splitext(f)[0]) and whose values are the approximate size of each file (humansize.approximate_size(meta.st_size)).
  4. As you saw in a previous example, there are six such files, thus there are six items in this dictionary.
  5. The value of each key is the string returned from the approximate_size() function.