Further adventures in array slicing.
Alex Martelli
aleax at mac.com
Fri May 4 22:35:55 EDT 2007
Steven W. Orr <steveo at syslang.net> wrote:
...
> I need to unpack this into three seperate arrays called name, fields,
> valid. The old code looked like this:
You're using lists, not arrays. If you DID want arrays, you'd have to
import standard library module array, and you'd be limited to a few
elementary types as items; it's pretty obvious that this is not what you
want -- nevertheless, why use the wrong name?
> names = []; fields = []; valid = []
> for ii in mdict:
> names.append(mdict[ii]['name'])
> fields.append(mdict[ii]['fields'])
> valid.append(mdict[ii]['valid'])
The order of keys in dictionary mdict is totally arbitrary, therefore
the order of items in those lists is going to be equally arbitrary; you
sure you _want_ that? Normally order IS significant in lists.
> I was very pleased with myself, except that the real world example of
> 'fields' and 'valid' is that they can be (but not always) a sequence.
Why would that make any difference at all?
> e.g.,
>
> mdefs = {0:{'name': 'Hello0',
> 'fields':(('Address', 8),
> ('Control', 8)),
> 'valid': {'Address': (1,255),
> 'Control': (33,44)}},
> 1:{'name': 'Hello1',
> 'fields':'fields1',
> 'valid': 'valid1'},
> 2:{'name': 'Hello2',
> 'fields':'fields2',
> 'valid': 'valid2'}}
>
> Is there a way to do this with possibly a more concise technique than the
> first for loop above?
not by much:
names = [v['name'] for v in mdict.itervalues()]
fields = [v['fields'] for v in mdict.itervalues()]
valid = [v['valid'] for v in mdict.itervalues()]
but this just saves a few characters, if that.
Alex
More information about the Python-list
mailing list