4 回答
TA贡献1770条经验 获得超3个赞
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)])
TA贡献2003条经验 获得超2个赞
应该
def compress(data):
res = []
for idx, sub in enumerate(data, start=0):
if idx == 0:
res.append(tuple(sub.keys()))
res.append([])
res[-1].append(tuple(sub.values()))
else:
res[-1].append(tuple(sub.values()))
return tuple(res)
TA贡献1876条经验 获得超6个赞
所以我创建了你想要的东西,你可以把它放在一个函数中,如果你愿意的话
data = [
{"a": 1, "b": 2, "c": 3},
{"a": 4, "c": 6, "b": 5}
]
keys = [[],[]]
for d in data:
items = list(d.items())
l = []
for i in items:
l.append(i[1])
if i[0] not in keys[0]:
keys[0].append(i[0])
else:
continue
keys[1].append(tuple(l))
keys = tuple(keys)
TA贡献1829条经验 获得超6个赞
使用列表理解:
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]}
添加回答
举报