naming objects from string

Wildemar Wildenburger wildemar at freakmail.de
Thu Sep 21 01:43:44 EDT 2006


manstey wrote:
> Hi,
> 
> thanks for the suggestions. this is my problem:
> 
> I have a metadata file that another user defines, and I don't know
> their structure in advance. They might have 300+ structures. the
> metadata defines the name and the tuple-like structure when read by
> python.
> 
> my program reads in the metadata file and then generates python tuples
> corresponding to their structures.
> 
> so they might provide a list of names, like 'bob','john','pete', with 3
> structures per name, such as 'apple','orange','red' and I need 9 tuples
> in my code to store their data:
> 
> bob_apple=()
> bob_orange=()
> ..
> pete_red=()
> 
> I then populate the 9 tuples with data they provide in a separate file,
> and the filled tuples are then validated against the metadata to make
> sure they are isomorphic.
> 
> Is this clear?
Erm, not exactly but I think I get it.

Note that creating empty tuples will mean that they will always be 
empty. They are immutable, basically meaning that you can not change 
them after they are created. If you want to create empty data that you 
want to fill later on, use lists. Or (which might be more convenient) 
put in the data right away).

Generally, since you do not know the names ('bob', 'john', etc.) and the 
structures in advance, the best way to store them is in a *variable*.
Here I would suggest dictionaries again. Let me write an example in 
pseudo python:

people = {}  # data dict
# lets suppose the data from your file is a list of tuples like:
# [('bob',('orange', 'apple', 'red')), ...]
# (I didnt quite get how your data is organized)
for name, structure in list_of_names_from_file:
     people[name] = {}  # make a new dict for the 'structures'
     for item in structure:
         people[name][item] = () # empty tuple
         # instead of an empty tuple you could fill in your data
         # right here, which would save you the extra keyboard mileage

Does that make sense in the context of your application?

wildemar



More information about the Python-list mailing list