簡體   English   中英

截斷 Python 字典的長度

[英]Truncate the length of a Python dictionary

給定一個有序的 Python 字典,截斷其長度的最 Pythonic 方法是什么? 例如,如果給我一本包含數千個條目的字典,我如何將其截斷為僅前 500 個條目。

你真的要在現場修改字典嗎? 您可以輕松生成一個新的(感謝迭代器,甚至沒有觸及您不需要的項目):

OrderedDict(itertools.islice(d.iteritems(), 500))

可以截斷原來的那個,但是對於大的那個來說效果會更差,並且可能不需要。 當然,如果其他人正在使用d ,則語義不同。

# can't use .iteritems() as you can't/shouldn't modify something while iterating it
to_remove = d.keys()[500:] # slice off first 500 keys
for key in to_remove:
    del d[key]

如果字典已經排序,你可以像這樣選擇你需要的元素數量

dict = json.loads(response.text)
dicts_result = dict['results']

dicts_result = dicts_result[:5] #This gives me 5 elements

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM