python 数据分类
#!/usr/bin/env python # coding: utf-8 import six from functools import partial from itertools import groupby def sort_items_by_key(items, key): result = {} for k, v in key.items(): ret = {} if isinstance(v, (six.string_types, six.integer_types)): tmp = filter(lambda x: x.get(k) == v, items) ret.setdefault(v, []).extend(tmp) elif isinstance(v, (list, set, tuple)): for vv in v: tmp = filter(lambda x: x.get(k) == vv, items) ret.setdefault(vv, []).extend(tmp) result.setdefault(k, []).append(ret) return result def test_items_key(): items = [ {"id": 1, "name": "atom", "age": 2}, {"id": 2, "name": "shylock", "age": 26}, {"id": 3, "name": "john", "age": 26} ] key = {"id": [1,2,3], "age": 26} print(sort_items_by_key(items, key)) def sort_key(item, key): return item.get(key) def test_items_key_groupBy(): result = {} items = [ {"id": 1, "name": "atom", "age": 25}, {"id": 1, "name": "shylock", "age": 26}, {"id": 3, "name": "john", "age": 26} ] for key in ["id", "age"]: func = partial(sort_key, key=key) result[key] = [{condition: list(numbers)} for condition, numbers in groupby(items, func)] print result if __name__ == "__main__": test_items_key() print("-"*10) test_items_key_groupBy()
output: {'age': [{26: [{'age': 26, 'id': 2, 'name': 'shylock'}, {'age': 26, 'id': 3, 'name': 'john'}]}], 'id': [{1: [{'age': 2, 'id': 1, 'name': 'atom'}], 2: [{'age': 26, 'id': 2, 'name': 'shylock'}], 3: [{'age': 26, 'id': 3, 'name': 'john'}]}]} ---------- {'age': [{25: [{'age': 25, 'id': 1, 'name': 'atom'}]}, {26: [{'age': 26, 'id': 1, 'name': 'shylock'}, {'age': 26, 'id': 3, 'name': 'john'}]}], 'id': [{1: [{'age': 25, 'id': 1, 'name': 'atom'}, {'age': 26, 'id': 1, 'name': 'shylock'}]}, {3: [{'age': 26, 'id': 3, 'name': 'john'}]}]}