Вы можете легко выполнить эту задачу, используя defaultdict
из collections
модуля:
from collections import defaultdict
test_list = [
{'text': "Hi",'bbox': (0,0)},
{'text': "There.",'bbox': (1,0)},
{'text': "Im",'bbox': (0,1)},
{'text': "John.",'bbox': (1,1)},
]
out = defaultdict(list)
for k in test_list:
out[k['bbox'][1]].append(k['text'])
# print(out.values())
print(list(out.values()))
# [['Hi', 'There.'], ['Im', 'John.']]
Обновление:
Вы можете также используйте объект по умолчанию Python dict
, как в этом примере:
out = {}
for k in test_list:
key, value = k['bbox'][1], k['text']
if key in out:
out[key].append(value)
else:
out[key] = [value]
print(list(out.values()))
# [['Hi', 'There.'], ['Im', 'John.']]