簡體   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