You can use itertools.groupby
. You can construct a lambda
expression that looks for the value corresponding to the 'command'
key, then finds the [1]
and [2]
elements of splitting on the ';'
character.
d =[{'name': 'fire', 'command': '1;2;3;4'},
{'name': 'brain', 'command': '2;2;3;4'},
{'name': 'word', 'command': '1;3;4;5'},
{'name': 'cellphone', 'command': '6;1;3;4'},
{'name': 'ocean', 'command': '9;3;7;4'}]
import itertools
groups = itertools.groupby(d, lambda i: i['command'].split(';')[1:3])
for key, group in groups:
print(list(group))
Output
[{'name': 'fire', 'command': '1;2;3;4'}, {'name': 'brain', 'command': '2;2;3;4'}]
[{'name': 'word', 'command': '1;3;4;5'}]
[{'name': 'cellphone', 'command': '6;1;3;4'}]
[{'name': 'ocean', 'command': '9;3;7;4'}]
To find groups that had more than one member, you need one more step:
for key, group in groups:
groupList = list(group)
if len(groupList) > 1:
print(groupList)
[{'command': '1;2;3;4', 'name': 'fire'}, {'command': '2;2;3;4', 'name': 'brain'}]