You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OrderedDict中获取每隔k个位置的键值对?

How to Create a New OrderedDict with Every k-th Element

Got it, let's work through this! The core issues you're probably hitting are either losing the OrderedDict type, messing up element selection, or breaking the original order. Here's how to fix it properly:

First, let's clarify what "every 2nd element" means—there are two common interpretations, and I'll cover both for flexibility:

  • Option 1: Pick elements starting from the first one, skipping every other (indices 0, 2, 4...)
  • Option 2: Pick elements starting from the second one, skipping every other (indices 1, 3, 5...)

Method 1: Using itertools.islice (Clean & Efficient)

This is my go-to for this kind of slicing, since it works directly with the ordered iterator from OrderedDict.items() and keeps things concise.

First, import the necessary modules:

from collections import OrderedDict
from itertools import islice

Example for your "every 2nd element" use case:

Let's start with a sample OrderedDict:

od1 = OrderedDict([
    ('key1', 'val1'),
    ('key2', 'val2'),
    ('key3', 'val3'),
    ('key4', 'val4'),
    ('key5', 'val5')
])
  • To get elements starting at index 0 (every 2nd element: first, third, fifth...):

    new_od = OrderedDict(islice(od1.items(), 0, None, 2))
    # Result: OrderedDict([('key1', 'val1'), ('key3', 'val3'), ('key5', 'val5')])
    
  • To get elements starting at index 1 (every 2nd element: second, fourth...):

    new_od = OrderedDict(islice(od1.items(), 1, None, 2))
    # Result: OrderedDict([('key2', 'val2'), ('key4', 'val4')])
    

The islice arguments here are: islice(iterator, start_index, end_index, step). Using None for end_index means we go all the way to the end of the dict.

Method 2: Enumerate & Filter (More Explicit)

If you prefer a more readable approach without itertools, you can enumerate the items and filter based on index:

def get_every_kth_od(original_od, k, start_index=0):
    return OrderedDict(
        (key, value) 
        for idx, (key, value) in enumerate(original_od.items()) 
        if idx % k == start_index
    )

# Usage for every 2nd element starting at index 1:
new_od = get_every_kth_od(od1, 2, 1)

Why Your Previous Attempt Might Have Failed

  • Returning a regular dict: If you used a standard dict comprehension, even in Python 3.7+ where dicts are ordered, you won't get an OrderedDict object. Always pass the filtered items to OrderedDict() to preserve the type.
  • Incorrect index logic: If you messed up the modulo condition or start index, you'd miss elements or pick the wrong ones. Double-check whether you want to start at index 0 or 1 for your "every k-th" requirement.

内容的提问来源于stack exchange,提问作者StatsSorceress

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:06:51