Skip to content

Instantly share code, notes, and snippets.

@KaySackey
Created February 7, 2016 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KaySackey/f170a0c1c28cb4026fb6 to your computer and use it in GitHub Desktop.
Save KaySackey/f170a0c1c28cb4026fb6 to your computer and use it in GitHub Desktop.
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