Guest User

Untitled

a guest
Jun 18th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. items = [{"pastel de belem" : ["Portugal", "Lisbon", "Belem"]},
  2. {"croissant" : ["Paris", "France"]},
  3. {"pizza" : ["Rome", "Italy", "Lisbon"]},
  4. {"bitoque" : ["Lisbon", "Portugal"]},
  5. {"laptop" : ["France", "Italy", Portugal"]}]
  6.  
  7. result = [{"Portugal" : ["pastel de belem", "laptop", "bitoque"]},
  8. {"Lisbon" : ["pastel de belem", "bitoque", "pizza"]},
  9. {"Belem" : ["pastel de belem"]},
  10. {"Paris" : ["croissant"]},
  11. {"France" : ["croissant", "laptop"]},
  12. {"Rome" : ["pizza"]},
  13. {"Italy" : ["pizza", "laptop"]}]
  14.  
  15. def get_location_names(items_array):
  16. result_array = []
  17. aux_dict = {}
  18. # iterates over the items list
  19. for index in range(len(items_array)):
  20. # gets the first key from the dict since we only have one anyway
  21. key = next(iter(items_array[index]))
  22. # iterates over the location list in each object
  23. for index2 in range(len(items_array[index][key])):
  24. aux_dict.setdefault(items_array[index][key][index2], []).append(key)
  25. # iterate over the aux_dict to make the final list with the objects inside
  26. for key, v in aux_dict.iteritems():
  27. result_array.append({key: v})
  28. return result_array
  29.  
  30. print get_location_names(items)
  31. # I think the result array is what you guys were expecting.
  32. # There might be room for more performance improvement, I would need to spend some serious time with it :)
Add Comment
Please, Sign In to add comment