如何从 OrderedDict 获取子集?

mar*_*lon 1 python

我在 Python 中有一个 OrderedDict,我只想获得第一个键值对。如何获得?例如,要获取前 4 个元素,我执行了以下操作:

subdict = {}

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

这是这样做的好方法吗?

Sha*_*ger 7

这种方法涉及遍历整个字典,即使您只需要前四个元素,一遍又一遍地检查索引,手动解包成对,以及不必要地手动执行索引检查。

使它短路很容易:

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]
Run Code Online (Sandbox Code Playgroud)

您可以嵌套解包以获得更好的名称:

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
Run Code Online (Sandbox Code Playgroud)

但你可以提升这个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
Run Code Online (Sandbox Code Playgroud)

在这一点上,您实际上可以将整个事情单行化(因为现在您有一个正好包含您想要的四对dict的可迭代对象,并且构造函数接受一个可迭代对象):

subdict = dict(islice(my_ordered_dict.items(), 4))
Run Code Online (Sandbox Code Playgroud)