curly-brace-aphobic?
D-Man
dsh8290 at rit.edu
Tue Jan 30 13:36:31 EST 2001
On Tue, Jan 30, 2001 at 05:54:26PM +0000, Mark Pilgrim wrote:
| 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
Doh!
| sequence. You need "for i in dict.keys(): print dict[i]".
how about what I meant:
for i in range( len( dict ) ) :
print dict[i]
and
for i in range( len( list ) ) :
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
Right, but the keys are integers, and range( len( ) ) (what I meant
to type) returns the integers in the proper order.
Defining the dict as:
dict = { 3:"three" , 1:"one" , 2:"two" }
would have the same effect, since range() will put the keys in the
desired order.
| dict.keys(): print dict[i]" and got the values in the reverse order from how
| I defined them ("three two one").
Ahh, but you were depending on dict.keys() to define the ordering for
you. I was (intending to) use range() to put the keys in their traditional,
numerical order.
|
| See http://diveintopython.org/odbchelper_dict.html for more on dictionaries,
| including a step-by-step example that illustrates this point.
|
Yes, this explains the way that dictionaries are used in practice. I
was thinking on a more generalized level where a list can be a special
case of a dictionary.
| -M
I just noticed another careless mistake in my original post:
for i in range() :
is zero-based indexing which works nicely for lists. For my example
dictionary it will fail since I used a one-based indexing (keying).
For my dictionary to behave as I meant to show it should be:
dict = { 0:"one" , 1:"two" , 2:"three" }
with the key-value pairs given in any order, of course.
-D
More information about the Python-list
mailing list