how do you get the name of a dictionary?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Aug 22 01:05:25 EDT 2006


On Mon, 21 Aug 2006 20:53:38 -0700, jojoba wrote:

> However, regarding your comment about the phone book, I have a
> question:
> You say:
> 
>> If you know a person's name, you can look up their number in the phone
>> book easily. If you know their phone number, it is much, much harder to
>> look up their name -- unless you go to the time and effort of keeping a
>> "reverse phone book".
> 
> 
> By reverse phone book, do you mean something like listing all the
> numbers in order, so as to optimize searching from phone number to
> name...

Something like that.

> and the implicaiton being that for python, it is much faster to
> find the data structure from the name, than the name from the data
> structure?
> If this is true, then you are quite right, and i am quite silly!
> I guess i was just thinking that all else equal, searching for one side
> (names) should be as fast as searching the other side (dictionaries),
> and hence recovering the mappings of name(s) to dictionary is equally
> fast both ways.
> If this is not true, then certainly, you are correct in saying that
> python need not spend its time managing a copious list of names and
> dictionaries.
> But does this really entail an overhaul of python to make such a thing
> happen?

Yes. Python uses dictionaries as "namespaces". When Python compiles a line
like "y = len(x) + 1", it parses the line into something vaguely like this:

(name y) (equals) (name len)(name x) (operator +) (value 1)

Then at run-time it looks up the names. It does this by keeping names in a
Python dictionary:

{'str': (object id 45), 'math': (object id 991), 'x': (object id 5065),
'b': (object id 9120), 'len': (object id 23), 'y': (object id 237), ... }

Notice that virtually everything in Python is in a namespace dictionary,
including modules and built-in functions. Keep in mind that there isn't
just one such namespace dictionary, there are lots of them, one for each
level of code. Classes have their own namespaces, so do modules. You can
explore two of these namespaces with the functions locals() and globals().

Because the namespace is a dictionary, it is easy to go from the name to
the object, but it is hard to go from the object to the name. And there
may be objects which exist, but don't have names: you won't find them in
the namespace dictionary at all.

What I've described is a simplification of what really happens, but it
gives you an idea of the basic principles.



-- 
Steven D'Aprano 




More information about the Python-list mailing list