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

如何在Python中批量修改特定QID对应的答案映射?

解决批量修改问卷答案的问题

Hey there! As a fellow Python learner, I get how tricky nested lists and dictionaries can feel at first. Let's break this down into simple, easy-to-follow steps to fix your problem.

核心思路

We'll keep this straightforward:

  1. Make a mapping dictionary to link number values (1-4) directly to their corresponding lowercase letters (a-d) — this is way cleaner than writing a bunch of if-else checks.
  2. Loop through each user's responses, target only the 2b and 2c QIDs, and swap out the number answers using our mapping.

完整代码示例

# Your original dataset
dd = [
    {
        "id": "abc",
        "age": "23",
        "response": [
            {"QID": "2a", "answer": "a"},
            {"QID": "2b", "answer": 2},
            {"QID": "2c", "answer": 1},
        ],
    },
    {
        "id": "cde",
        "age": "20",
        "response": [
            {"QID": "2a", "answer": "b"},
            {"QID": "2b", "answer": 2},
            {"QID": "2c", "answer": 2},
        ],
    },
    {
        "id": "dfe",
        "age": "21",
        "response": [
            {"QID": "2a", "answer": "a"},
            {"QID": "2b", "answer": 3},
            {"QID": "2c", "answer": 4},
        ],
    },
]

# Define the number-to-letter mapping (matches your target lowercase format)
answer_conversion = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

# Iterate over each user in the dataset
for user in dd:
    # Loop through every response item for the current user
    for response in user["response"]:
        # Only modify answers for QID 2b or 2c
        if response["QID"] in ("2b", "2c"):
            # Swap the number answer with its corresponding letter
            response["answer"] = answer_conversion[response["answer"]]

# Print the modified dataset to verify the result
print(dd)

代码细节解释

  • answer_conversion:This dictionary acts as a quick lookup table. Instead of writing if answer == 1: change to 'a' over and over, we just use the number as a key to get the right letter.
  • Double loops:The first loop goes through each user's data, and the second loop digs into their individual responses. This makes it easy to target exactly the items we need.
  • Direct modification:Since dictionaries in Python are mutable objects, changing response["answer"] updates the original dataset automatically — no need to create extra copies or complex structures.

Run this code, and your dd dataset will match exactly the target format you shared!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:42:33