Pythonic way to condese my array

James Stroud jstroud at mbi.ucla.edu
Wed Sep 20 00:55:25 EDT 2006


Dean Card wrote:
> I have a list of dictionaries where each dictionary defines, among other 
> things, a row and column number.  So, my list might look like this:
> [{'row':1, 'column':1, otherdata}, {'row':1, 'column':2, 'otherdata}...]
> 
> This data is passed to flash and used there to create a grid of objects that 
> are placed based on the row and column values.
> 
> For a given set of data I may have values column values in the range of 1, 9 
> inclusive.
> 
> What I would like to do is take my list of dictionaries (like the one listed 
> above) and shift the column numbers down to fill in missing values... 
> example (only the column key,value pair is show for simplification):
> 
> [{'column':1}, {'column':2}, {'column', 4}, {'column': 8}, {'column':2}, 
> {'column', 4}]
> 
> If this were the dataset... I would want to change all 4s to 3 and all 8s to 
> 4.  That way I end up with 1 ...  4 instead of 1, 2, 4, and 8.
> 
> Is there some slick way to do this?
> 
> Thanks
> 
> 

Not sure how slick this is, but I would do it thus:

dicts = [{'column':1}, {'column':2}, {'column': 4}, {'column': 8}, 
{'column':4}]

vals = list(set(d['column'] for d in dicts))
vals.sort()
amap = dict((b,a) for (a,b) in enumerate(vals))

for d in dicts:
   d['column'] = amap[d['column']] + 1


The "1" in the last line comes from your requirement to start numbering 
at 1 instead of 0.

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list