考虑以下列表字典,d:
{
'ra': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'decl': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'source_id': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'priority': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
}
我想返回一个字典,其中包含 <= 列表中每个字典键的前 N 个值。因此如果 N = 4
,它应该返回
{
'ra': [0, 1, 2, 3],
'decl': [0, 1, 2, 3],
'source_id': [0, 1, 2, 3],
'priority': [0, 1, 2, 3],
}
或者如果列表少于 4 个条目,则返回完整列表。有点像 .head(N)
适用于数据框。
我可以将字典转换为数据框,执行 .head(N)
操作并将其转换回字典,但似乎必须有一种更简单/更 Pythonic 的方法来做到这一点。
答案 0 :(得分:5)
我会使用字典理解来做一些事情
lessen = {
'ra': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'decl': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'source_id': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'priority': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
}
limit = 4
new = {k:v[:limit] for k,v in lessen.items()}
输出
{'ra': [0, 1, 2, 3], 'decl': [0, 1, 2, 3], 'source_id': [0, 1, 2, 3], 'priority': [0, 1, 2, 3]}
答案 1 :(得分:0)
用一个简单的 for
循环很容易做到:
N = 4
for key in thedata:
thedata[key] = thedata[key][:N]
答案 2 :(得分:0)
你可以使用
dct = {
'ra': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'decl': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'source_id': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'priority': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
}
new_dct = {key: values[0:4] for key, values in dct.items()}
print(new_dct)