簡體   English   中英

如何從 OrderedDict 中獲取子集?

[英]How to get a subset from an OrderedDict?

我在 Python 中有一個 OrderedDict,我只想獲得第一個鍵值對。 如何獲得? 例如,要獲取前 4 個元素,我執行了以下操作:

subdict = {}

for index, pair in enumerate(my_ordered_dict.items()):
    if index < 4:
       subdict[pair[0]] = pair[1]

這是這樣做的好方法嗎?

該方法涉及遍歷整個字典,即使您只需要前四個元素,一遍又一遍地檢查索引,手動解包對,並手動執行不必要的索引檢查。

使其短路很容易:

subdict = {}
for index, pair in enumerate(my_ordered_dict.items()):
    if index >= 4:
       break  # Ends the loop without iterating all of my_ordered_dict
    subdict[pair[0]] = pair[1]

你可以嵌套拆包以獲得更好的名字:

subdict = {}
# Inner parentheses mandatory for nested unpacking
for index, (key, val) in enumerate(my_ordered_dict.items()):
    if index >= 4:
       break  # Ends the loop
    subdict[key] = value

但您可以使用itertools.islice改進它以刪除手動索引檢查:

from itertools import islice  # At top of file

subdict = {}
# islice lazily produces the first four pairs then stops for you
for key, val in islice(my_ordered_dict.items(), 4):
    subdict[key] = value

在這一點上你實際上可以將整個事情連成一行(因為現在你有一個你想要的四對的可迭代,並且dict構造函數接受一個可迭代的對):

subdict = dict(islice(my_ordered_dict.items(), 4))

您可以使用 map function,像這樣

item = dict(map(lambda x: (x, subdict[x]),[*subdict][:4]))

這是一種方法:

sub_dict = dict(pair for i, pair in zip(range(4), my_ordered_dict.items()))

zip(a,b)的長度等於ab中最短者的長度,因此如果my_ordered_dict.items()長於4zip(range(4), my_ordered_dict.items()只取第一個4項。這些鍵值對被傳遞給內置的dict以生成新的dict

暫無
暫無

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

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