python - Split list of dictionaries into chunks -


i have python list 2 list inside(one each room - there 2 rooms), dictionaries inside.

how can transform this:

a = [         [{'rate': decimal('669.42000'), 'room': 2l, 'name': u'10% off'},           {'rate': decimal('669.42000'), 'room': 2l, 'name': u'10% off'},           {'rate': decimal('632.23000'), 'room': 2l, 'name': u'15% off'},           {'rate': decimal('632.23000'), 'room': 2l, 'name': u'15% off'}],          [{'rate': decimal('855.36900'), 'room': 3l, 'name': u'10% off'},           {'rate': decimal('855.36900'), 'room': 3l, 'name': u'10% off'}] ] 

into this:

a = [         [{'rate': decimal('669.42000'), 'room': 2l, 'name': u'10% off'},           {'rate': decimal('669.42000'), 'room': 2l, 'name': u'10% off'}],         [{'rate': decimal('632.23000'), 'room': 2l, 'name': u'15% off'},           {'rate': decimal('632.23000'), 'room': 2l, 'name': u'15% off'}],          [{'rate': decimal('855.36900'), 'room': 3l, 'name': u'10% off'},           {'rate': decimal('855.36900'), 'room': 3l, 'name': u'10% off'}] ] 

i need create in main list, 3 lists inside. 1 each type of promo. thanks

using itertools.groupby, use nested comprehension:

>>> itertools import groupby >>> pprint import pprint  >>> x = [list(g) l in k, g in groupby(sorted(l))] >>> pprint(x) [[{'name': u'10% off', 'rate': decimal('669.42000'), 'room': 2l},   {'name': u'10% off', 'rate': decimal('669.42000'), 'room': 2l}],  [{'name': u'15% off', 'rate': decimal('632.23000'), 'room': 2l},   {'name': u'15% off', 'rate': decimal('632.23000'), 'room': 2l}],  [{'name': u'10% off', 'rate': decimal('855.36900'), 'room': 3l},   {'name': u'10% off', 'rate': decimal('855.36900'), 'room': 3l}]] 

you can provide key function both sorted , groupby (preferably same) in order group specific property:

from operator import itemgetter fnc = itemgetter('rate')  # if want group rate x = [list(g) l in k, g in groupby(sorted(l, key=fnc), key=fnc)] 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -