Pythonic way to condese my array

Robert Kern robert.kern at gmail.com
Wed Sep 20 00:53:58 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?

Untested, but intended for Python 2.4:

list_o_dicts = [{'column': 1}, ...]
columns = set(x['column'] for x in list_o_dicts)
column_map = dict((column, i+1) for i, column in enumerate(sorted(columns)))
for d in list_o_dicts:
     d['column'] = column_map[d['column']]

Of course, code that I wouldn't get fired for would have a slightly greater line 
count and fewer one-letter variable names.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list