0

I have a list of dictionaries:

[
    {'student_id': 'john', 'exercise_id': '3', 'answer': 20},
    {'student_id': 'john', 'exercise_id': '2', 'answer': 10},
    {'student_id': 'jane', 'exercise_id': '2', 'answer': 30},
]

What is an elegant/short way to convert that into a [exercise x student] "mapping table" dictionary? Like so:

{
    '3':{
        'john': {'student_id': 'john', 'exercise_id': '3', 'answer': 20}
    },
    '2': {
        'john': {'student_id': 'john', 'exercise_id': '2', 'answer': 10},
        'jane': {'student_id': 'jane', 'exercise_id': '2', 'answer': 30}
    }
}

You can assume the map contains at most one answer per exercise per student.

2

2 Answers 2

3

The straight forward way would be to gather them in a dictionary, like this

d = {}
for item in l:
    d.setdefault(item["exercise_id"], {}).setdefault(item["student_id"], []).append(item)
print(d)

Output

{'2': {'jane': [{'answer': 30, 'exercise_id': '2', 'student_id': 'jane'}],
       'john': [{'answer': 10, 'exercise_id': '2', 'student_id': 'john'}]},
 '3': {'john': [{'answer': 20, 'exercise_id': '3', 'student_id': 'john'}]}}

First, if the item["exercise_id"] is not there in d, then a new dictionary will be set as the value and then in that dictionary, if item["student_id"] is not there, we set an empty list as the value and we append the current dictionary in that list.

1
  • Upvoted for short answer plus explanation. Will mark friedi's answer as correct though because it produces the exact desired output. Although this construct will probably be useful in the future too. Thanks!!!! Oct 22, 2014 at 13:25
2

This generates the output you want:

output = {}
for value in data:
    output.setdefault(value['exercise_id'], {})[value['student_id']] = value

print output
1
  • Instead of calling setdefault(_, {}) you can use change type of output from dict to defaultdict(dict), see more in docs docs.python.org/2/library/…
    – NickAb
    Oct 22, 2014 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.