Created
February 7, 2016 03:41
-
-
Save KaySackey/f170a0c1c28cb4026fb6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment