[Tutor] Problems with partial string matching

Steven D'Aprano steve at pearwood.info
Tue Nov 2 00:56:38 CET 2010


Josep M. Fontana wrote:
>> The only time year is bound is in the previous loop, as I said.  It's the
>> line that goes:
>>     name, year = line.strip.....
>>
>> So year is whatever it was the last time through that loop.
> 
> OK, this makes sense. Indeed that is the value in the last entry for
> the dictionary. Thanks a lot again.


Dictionaries don't have a "last", or "first", entry -- they're unordered 
collections. Think of them as a bag filled with stuff -- if you reach in 
and grab an item, one at a time, you will get the items in some order, 
but that's imposed on the bag by the sequential nature of taking one 
item at a time. The items themselves have no order.

Iterating over a dictionary, or printing it, is like dipping into the 
bag for each item one at a time. Python carefully ensures that this 
order is consistent: dict,keys(), dict.values() and dict.items() will 
return the objects in the same order, so long as you don't modify the 
dictionary between calls. But that order is arbitrary, depends on the 
history of insertions and deletions, and is subject to change without 
notice. So if we do this:

d = {}
d[0] = 'a'
d[-1] = 'b'
d[-2] = 'c'

and then print d in Python 3.1.1, we get: {0: 'a', -2: 'c', -1: 'b'}

but if we add the items in a different order:

d = {}
d[-2] = 'c'
d[0] = 'a'
d[-1] = 'b'

we get this instead: {0: 'a', -1: 'b', -2: 'c'}.


In general, there is no relationship between the order you insert 
objects into a dict and the order that you will get them out. Sometimes 
it may match. Usually it won't.


-- 
Steven



More information about the Tutor mailing list