Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data = [
- {
- "id": 1,
- "type": "Color",
- "tag": "Blue"
- },
- {
- "id": 2,
- "type": "Color",
- "tag": "Red"
- },
- {
- "id": 3,
- "type": "Shape",
- "tag": "Square"
- },
- ]
- expected = [
- {
- "type": "Color",
- "tags": [
- {
- "id": 1,
- "tag": "Blue"
- },
- {
- "id": 2,
- "tag": "Red"
- }
- ]
- },
- {
- "type": "Shape",
- "tags": [
- {
- "id": 3,
- "tag": "Square"
- }
- ]
- }
- ]
- from collections import defaultdict
- def transform_result(data):
- # Make a dictionary for each type first, since it simplifies things
- type_map = defaultdict(list)
- for entry in data:
- _id, _type, _tag = entry['id'], entry['type'], entry['tag']
- type_map[_type].append({
- 'id': _id,
- 'tag': _tag,
- })
- # Make the container {type: __, tags: ___}
- ret = []
- for key, value in type_map.items():
- ret.append({
- 'type': key,
- 'tags': value
- })
- return ret
- assert(transform_result(data) == expected)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement