[Tutor] List's name in a string

"Héctor Villafuerte D." hec.villafuerte at telgua.com.gt
Tue Sep 30 18:17:31 EDT 2003


Jeff wrote:

> Okay, you've got multiple lists that you want to apply the above 
> treatment to.  You can keep those lists in a dictionary, like so:
>
> list_dict = { 'LIST1': ['file1', 'file2', 'file3'],
>               'LIST2': ['otherfile1', 'otherfile2'] }
>
> And then you can iterate over the items in the dictionary:
>
> for listname, filelist in list_dict.items():
>     outfile_name = "%s_proc" % listname
>     outfile = file(outfile_name, 'w')
>     for filename in filelist:
>         # ...
>
> If you want to build the lists of filenames on the fly, that's fine, 
> too.  Just assemble the list of files, generate a unique name, and 
> plug them into the dictionary --
>
> list_dict[name] = filelist
>
> Or, say you have a long list of files that you're trying to categorize 
> into different sublists.  You can use dict.get() to make this easier 
> -- get() will return a default value if a key isn't found in the 
> dictionary.
>
> list_dict = {}
> for filename in big_filelist:
>     key = category(filename)
>     existing = list_dict.get(key, [])
>     existing.append(filename)
>     list_dict[key] = existing
>
> Hopefully this will give you some ideas on how to handle the specifics 
> of your problem...
>

Great, thanks!
Dictionaries will make it... I knew all those new data structures would 
be useful someday :)




More information about the Tutor mailing list