Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrEaKmAn/dc1f39ff7ade55a90dfa9581289ef6e3 to your computer and use it in GitHub Desktop.
Save FrEaKmAn/dc1f39ff7ade55a90dfa9581289ef6e3 to your computer and use it in GitHub Desktop.
from collections import OrderedDict
input = [{
'name': 'Product1',
'locations': ['Paris', 'London', 'Ljubljana']
}, {
'name': 'Product2',
'locations': ['Berlin', 'London', 'New York']
}]
# try to atleast obtain some order, otherwise normal dict is just fine
locations = OrderedDict()
for product in input:
for location in product['locations']:
if location not in locations:
locations[location] = []
locations[location].append(product['name'])
output = [{'location': location, 'products': products} for location, products in locations.items()]
print(output)
"""
[{
'products': ['Product1'],
'location': 'Paris'
},
{
'products': ['Product1', 'Product2'],
'location': 'London'
},
{
'products': ['Product1'],
'location': 'Ljubljana'
},
{
'products': ['Product2'],
'location': 'Berlin'
},
{
'products': ['Product2'],
'location': 'New York'
}]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment