[Tutor] Deleted dictionary length not reporting

Steven D'Aprano steve at pearwood.info
Wed Jul 17 04:04:56 CEST 2013


On 17/07/13 11:48, Jim Mooney wrote:
> This is puzzling me. I have a folder with about 125 movie sound clips,
> like "I'll be back," blues brothers theme, oompa-loompas, etc. I play
> seven random ones on windows startup, which works fine. But just so I
> don't repeat a clip, I delete it from the dictionary on each go-round.
> However, to make sure that happened, I printed the key-length on each
> go-round.  It should be shorter by one every time but I always get a
> length of 125. (Yes, I know there are about five different ways to do
> this, but I thought I'd try a dictionary ;')


That's because your loop recreates the dictionary at the start of each loop. I bet you have 126 WAV files in the directory. You play one, delete it from the dict, print the number of keys (which will be 126-1 = 125), and then start the loop again, which recreates the dict good as new.


> Also, the printout doesn't occur until after all the sounds play, so
> maybe that has something to do with it. But I also tried saving the
> lengths in a list while the program ran, and got the same result. A
> list of all '125'

That's very strange. print is not supposed to be buffered, it should always print immediately. I have no ideas about that.



> #Using Python 2.7 on Win 7
>
> import winsound
> import random, os
> random.seed()
>
> lenlist = []
> file_list = os.listdir('WAV')
>
> for clip in range(0,7):
>      file_dict = dict(enumerate(file_list))
>      sound_key = random.choice(range(0,len(file_list)))


Here's a better way to do it, which guarantees that there will be no duplicates (unless you have duplicate files):

file_list = os.listdir('WAV')
random.shuffle(file_list)
for name in file_list[:7]:
     winsound.PlaySound('WAV/' + name, winsound.SND_FILENAME)



-- 
Steven


More information about the Tutor mailing list