Created
May 9, 2018 20:50
-
-
Save FrEaKmAn/dc1f39ff7ade55a90dfa9581289ef6e3 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
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