Cleaning up conditionals

Deborah Swanson python at deborahswanson.net
Tue Jan 3 04:18:26 EST 2017


Chris Angelico wrote, on January 03, 2017 12:14 AM
> 
> On Tue, Jan 3, 2017 at 6:35 PM, Deborah Swanson 
> <python at deborahswanson.net> wrote:
> > I think I'm right that core python sequences can't be 
> indexed in any 
> > fashion by strings, because strings aren't iterable. I suppose it 
> > might be possible for strings to be iterable in some sort of ascii 
> > char code order, but that seems like it could get real whacky very 
> > fast, and not terribly useful.
> 
> It's not because they're not iterable, but because there's a 
> fundamental difference between a key-value pair (dict) and a 
> sequence. You can combine the two in several different ways, 
> none of which is the "one most obvious". Python's OrderedDict 
> retains the order of its keys; in contrast, a namedtuple is a 
> "record" type with a fixed set of keys that correspond to 
> positions in the record. In your case, I think a namedtuple 
> would be a good fit, but there's no general concept of 
> indexing a sequence with strings.
> 
> ChrisA

I hope I can get to namedtuples tomorrow, they do sound like an
excellent data structure for the purpose of using field titles as
subscripts. I'd never heard of them before, so I'm looking forward to
finding out what they are and how they work.

OrderedDict is the new development I'd read about, but I think the key
order is just the order keys were added to the dict. The nice thing
about that though is when you loop over a dict you will always get the
key/value pairs in the same order, where with the standard dict they
come out in arbitrary order. Very disconcerting if you're watching the
loop as it progresses over muiltiple executions. I imagine you could
sort an OrderedDict so the keys originally added randomly would be put
into some kind of good order.





More information about the Python-list mailing list