如何在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:
- 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.
- Loop through each user's responses, target only the
2band2cQIDs, 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 writingif 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
相关产品推荐
相关产品推荐

