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

如何基于原字典奇偶位置的值创建键值配对的新字典?

Solution for Pairing Dictionary Values into New Key-Value Pairs

Let’s break this down clearly: you have a dictionary where each key maps to a single-element list, and you want to pair every odd-positioned value (1st, 3rd, 5th...) as the new key, with the next even-positioned value (2nd, 4th, 6th...) as its corresponding value (still wrapped in a list). Here’s a scalable approach that works for any number of elements:

Approach

  1. Enforce Order: Since keys like key1, key2 are strings, we need to sort them numerically to ensure we process values in the correct sequence (critical for Python versions pre-3.7, where dictionaries don’t preserve insertion order).
  2. Extract Raw Values: Pull out the actual values from the original dictionary’s single-element lists.
  3. Pair Consecutive Elements: Iterate over the extracted values in steps of 2, building the new dictionary by pairing each element with the next one.

Code Implementation

original_dict = {'key1': ['value1'], 'key2': ['value2'], 'key3': ['value3'], 'key4': ['value4']}

# Step 1: Sort keys numerically to maintain the intended order
sorted_keys = sorted(original_dict.keys(), key=lambda k: int(k.replace('key', '')))

# Step 2: Extract the actual values from each single-element list
values_list = [original_dict[key][0] for key in sorted_keys]

# Step 3: Build the new dictionary by pairing consecutive elements
new_dict = {}
for i in range(0, len(values_list), 2):
    if i + 1 < len(values_list):  # Handle odd number of elements gracefully
        new_dict[values_list[i]] = [values_list[i+1]]

print(new_dict)
# Output: {'value1': ['value2'], 'value3': ['value4']}

Explanation

  • Sorting Keys: The lambda function strips the key prefix from each key and converts the remaining string to an integer, ensuring key10 comes after key9 (instead of the alphabetical order that would place it before).
  • Extracting Values: We loop through sorted keys and grab the first (and only) element from each list in the original dictionary.
  • Pairing Elements: Using range(0, len(values_list), 2) lets us jump by 2 each iteration, pairing elements at indices 0&1, 2&3, etc. The check i+1 < len(values_list) prevents index errors if there’s an odd number of elements (the last unpaired value will be skipped).

Edge Cases to Note

  • Odd Number of Elements: If your original dict has an odd count of key-value pairs, the final value won’t have a pair and will be excluded from the new dict. You can adjust this logic (e.g., add it with a default value) if needed.
  • Non-Standard Key Names: If your keys don’t follow the keyN pattern, tweak the sorting logic to match your actual key naming convention (or skip sorting entirely if using Python 3.7+ and insertion order is already correct).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:24:33