curly-brace-aphobic?
Mark Pilgrim
f8dy at my-deja.com
Tue Jan 30 12:54:26 EST 2001
In article <mailman.980870616.378.python-list at python.org>,
D-Man <dsh8290 at rit.edu> wrote:
> | An essential difference is the fact that lists are ordered, but dicts aren't.
>
> Suppose I use a dict with integers as keys. How is this different from a list?
>
> dict = { 1:"one" , 2:"two" , 3:"three" }
> list = [ "one" , "two" , "three" ]
>
> for i in len( list ) :
> print list[i]
>
> for i in len( dict ) :
> print dict[i]
>
> In this case, they are identical!
First, "for i in len(dict): print dict[i]" will give you a "loop over
non-sequence" error, because len returns an integer, and for requires a
sequence. You need "for i in dict.keys(): print dict[i]".
Second, "for i in dict.keys(): print dict[i]" is not the same as "for i in
list: print list[i]" because dictionaries are unordered. I'm not really
talking in circles here (I'm talking in sequences... no, never mind). Just
because you defined dict in a particular order doesn't mean that the keys
stay in that order. For instance, on my machine, just now, I did "for i in
dict.keys(): print dict[i]" and got the values in the reverse order from how
I defined them ("three two one").
See http://diveintopython.org/odbchelper_dict.html for more on dictionaries,
including a step-by-step example that illustrates this point.
-M
--
You're smart; why haven't you learned Python yet? http://diveintopython.org/
Sent via Deja.com
http://www.deja.com/
More information about the Python-list
mailing list