繁体   English   中英

从列表的字典中返回包含每个键的前 N 个列表条目的字典

[英]Return a dict containing the first N list entries for each key from a dict of lists

考虑以下列表字典 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 的方法来做到这一点。

我会 go 使用字典理解的东西

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()}

output

{'ra': [0, 1, 2, 3], 'decl': [0, 1, 2, 3], 'source_id': [0, 1, 2, 3], 'priority': [0, 1, 2, 3]}

使用简单for循环很容易做到:

N = 4
for key in thedata:
    thedata[key] = thedata[key][:N]

您可以使用

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM