Best way to add a "position" value to each item in a list

Sean sberry2a at gmail.com
Thu Jul 9 16:33:01 EDT 2009


On Jul 9, 1:16 pm, Sean <sberr... at gmail.com> wrote:
> I have a huge list, 10,000,000+ items.  Each item is a dictionary with
> fields used to sort the list.  When I have completed sorting I want to
> grab a page of items, say 1,000 of them which I do easily by using
> list_data[x:x+1000]
>
> Now I want to add an additional key/value pair to each dictionary in
> the list, incrementing them by 1 each time.  So, if I grabbed page 2
> of the list I would get:
>
> [{'a':'a', 'b':'b', 'position':1001}, {'c':'c', 'd':'d', 'position':
> 1002}, ...]
>
> Any way to do that with list comprehension?  Any other good way to do
> it besides iterating over the list?
>
> Thanks

I was able to do this by doing the following:
page_data = [[start_position + 1 + n, x] for n, x in enumerate
(page_data)]

However, this creates a list of lists, each containing an int and a
dictionary.  I wanted to add it directly to the dictionary.  I can add
the key position to the dictionary when the data is created, but how
would I assign the value in a list comprehension?




More information about the Python-list mailing list