德玛西亚99
def compress(data): result = [] keys = tuple(data[0].keys()) # the keys result.append(keys) result2 = [] result2.append(tuple([data[0][key] for key in keys])) result2.append(tuple([data[1][key] for key in keys[::-1]])) result.append(result2) return tuple(result)data = [ {"a": 1, "b": 2, "c": 3}, {"a": 4, "c": 6, "b": 5}]print(compress(data))印刷:(('a', 'b', 'c'), [(1, 2, 3), (6, 5, 4)])
肥皂起泡泡
使用列表理解:def compress(data): keys = tuple(sorted(data[0].keys())) values = [tuple(d[k] for k in keys) for d in data] return (keys, values)>>> compress([{"a": 1, "b": 2, "c": 3},{"a": 4, "c": 6, "b": 5}])(('a', 'b', 'c'), [(1, 2, 3), (4, 5, 6)])可选:缺少钥匙如果某些字典中可能缺少某些键,您可以使用所有字典中的所有键,然后使用 删除重复的键set,然后使用d.get(k, default_value)代替d[k]:def compress(data, default_value=None): keys = tuple(sorted(set(k for d in data for k in d.keys()))) values = [tuple(d.get(k, default_value) for k in keys) for d in data] return (keys, values)>>> data = [{'a':1, 'b': 2, 'c': 3}, {'a':11, 'b':12, 'd':14}]>>> compress(data, 0)(('a', 'b', 'c', 'd'), [(1, 2, 3, 0), (11, 12, 0, 14)])可选:存储此数据的另一种方式您可以将此字典列表重构为列表字典:def refactor(data): keys = data[0].keys() return { k: [d[k] for d in data] for k in keys }>>> refactor([{"a": 1, "b": 2, "c": 3},{"a": 4, "c": 6, "b": 5}]){'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}同样,您可以小心丢失密钥:def refactor(data): keys = set(k for d in data for k in d.keys()) return { k: [d[k] for d in data if k in d] for k in keys }>>> refactor([{'a':1, 'b': 2, 'c': 3}, {'a':11, 'b':12, 'd':14}]){'d': [14], 'a': [1, 11], 'c': [3], 'b': [2, 12]}