Create a sublist from list of dictionaries

  dictionary, python

I want to create a sublist from current list of dictionaries base on dictionary key.

My data:

[{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]

Data which I want to achieve:

[ [{'0': 2}, {'0': 1}], [{'1': 2}], [{'2': 2}, {'2': 2}] ]

As you can see internal arrays contain a dictionary with the same value of the key.

My code current code is like:

dicts = [ [{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}], [{'0': 2}, {'1': 3}, {'2': 2}, {'2': 2}], 
[{'0': 2}, {'0': 4}, {'1': 2}, {'1': 1}] ]

ex_list = []
sublist = []
for group in dicts:
  if group.keys() in sublist:
    sublist.append(group)
  else:
    sublist.append(group)
    if group.keys() != sublist[-1]:
      sublist = []
      sublist.append(group)
ex_list.append(sublist)

Any help highly appreciated.

Source: Python Questions

LEAVE A COMMENT