Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1.  
  2. data = [
  3. {
  4. "id": 1,
  5. "type": "Color",
  6. "tag": "Blue"
  7. },
  8. {
  9. "id": 2,
  10. "type": "Color",
  11. "tag": "Red"
  12. },
  13. {
  14. "id": 3,
  15. "type": "Shape",
  16. "tag": "Square"
  17. },
  18. ]
  19.  
  20. expected = [
  21. {
  22. "type": "Color",
  23. "tags": [
  24. {
  25. "id": 1,
  26. "tag": "Blue"
  27. },
  28. {
  29. "id": 2,
  30. "tag": "Red"
  31. }
  32. ]
  33. },
  34. {
  35. "type": "Shape",
  36. "tags": [
  37. {
  38. "id": 3,
  39. "tag": "Square"
  40. }
  41. ]
  42. }
  43. ]
  44.  
  45. from collections import defaultdict
  46. def transform_result(data):
  47. # Make a dictionary for each type first, since it simplifies things
  48. type_map = defaultdict(list)
  49. for entry in data:
  50. _id, _type, _tag = entry['id'], entry['type'], entry['tag']
  51. type_map[_type].append({
  52. 'id': _id,
  53. 'tag': _tag,
  54. })
  55. # Make the container {type: __, tags: ___}
  56. ret = []
  57. for key, value in type_map.items():
  58. ret.append({
  59. 'type': key,
  60. 'tags': value
  61. })
  62. return ret
  63.  
  64. assert(transform_result(data) == expected)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement