[Tutor] user-given variable names for objects

Luke Paireepinart rabidpoobear at gmail.com
Thu Dec 13 08:58:10 CET 2007


Che M wrote:
> I'm sure this is a classic beginner's topic, and I've read a bit about 
> it online already, but I'd like to ask about it here as well.  I want 
> to assign names to objects based on what a user inputs so that I can 
> later keep track of them.
Yes, this comes up quite a bit.
> In particular, I want to time multiple events by getting each of their 
> start times and later comparing them to their respective stop times--I 
> don't want to user timers.  In order to do this, I need to give each 
> start time a name associated with the name of the event.  If there is 
> an "event A" it's start time could be eventA_start, whereas event B 
> could be called eventB_start, i.e.:
>
> eventA_start = datetime.datetime.now()
>
> The problem is, I don't know the "A" part...the user could choose 
> eventPotato or eventDinosaur.  I won't know in advance.  I want the 
> name chosen/inputted by the user to be attached to the name for the 
> time that event started.
>
> I have read that the way to do this properly in Python is with use of 
> dictionaries, but I haven't found a reference online that shows how to 
> do it is in a complete way.  Any help is appreciated.
There are a multitude of different ways this can be accomplished with 
dictionaries.  It really depends on what structure you want your data to 
follow.
By way of example, suppose we want to store the start time and length of 
timers from the user.
We could have an input loop as such:
import time
eventData = {}
while True:
    name, duration = raw_input("Name your event (done to exit): "), 
int(raw_input("How long should it last? "))
    if name.strip().lower() == "done":
        break

now we want to add the user's data to our dictionary so we can keep 
track of events.

    eventData[name] = time.time() + duration

note that I used the time.time() function to get the current time and 
just added duration to it,
so every event now stores the ending time of the event (when we want to 
trigger it, say)

given this time, we can generate a list of all events that have happened 
in the past,
using list comprehensions or by other methods:
[a for a in eventData.keys() if eventData[a] < time.time()]

then we can simply print out all events that have already occurred at 
any point in time:
while True:
    finished = [a for a in eventData.keys() if eventData[a] < time.time()]
    print "The following events have occurred: "
    for name in finished:
        print name
    time.sleep(1)
    if len(finished) == len(eventData.keys()):
        break

Of course this is by no means an ideal solution, it merely serves as an 
example.

Does this make sense, and do you understand why it's better to use 
dictionaries than to use variables
to achieve this?
[note - no code was tested, not guaranteed to work :)]
-Luke


More information about the Tutor mailing list