Further adventures in array slicing.

Steven W. Orr steveo at syslang.net
Fri May 4 17:03:38 EDT 2007


This is more for my education and not so much for practicality.

I have a structure that sort of looks like this:

mdict = {33:{'name': 'Hello0',
             'fields':'fields0',
             'valid': 'valid0'
          55:{'name': 'Hello1',
             'fields':'fields1',
             'valid': 'valid1'},
          14:{'name': 'Hello2',
             'fields':'fields2',
             'valid': 'valid2'}}

i.e, each element of the dictionary is itself a dictionary with three 
common keys.

I need to unpack this into three seperate arrays called name, fields, 
valid. The old code looked like this:

names = []; fields = []; valid = []
for ii in mdict:
     names.append(mdict[ii]['name'])
     fields.append(mdict[ii]['fields'])
     valid.append(mdict[ii]['valid'])

I tried this (to see if it would work) and it seems to work just fine:

def u2(m):
     aa = [ms[ii][jj] for jj in 'name','fields','valid' for ii in m]
     return tuple(zip(aa[0::3], aa[1::3], aa[2::3]))
names,fields,valid = u2(mdict)

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. 
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?

A second question is: When can you use += vs .append(). Are the two always 
the same?

Thanks. :-)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



More information about the Python-list mailing list