On Thu, Jul 9, 2009 at 4:16 PM, Sean<sberr...@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?
Normally you wouldn't mutate the items in a list with a list comprehension. Instead, you would use a for loop, like this: for idx,item in enumerate(my_list_of_dicts): item['position'] = idx Is there a particular reason you want to do this with a list comprehension? Using a list comp means you're going to create an extra copy of your 10 million item list, just so you can add a key to each member, then (probably) throw away the original list. It doesn't seem like the right tool for the job here. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list