I have such a list:
original_list = [
{
amenity: "Parking",
amount: 120,
version: 1,
percentage: 4,
id: 1
},
{
amenity: "Pool",
amount: 300,
version: 2,
percentage: 10,
id: 5,
},
{
amenity: "Pool",
amount: 200,
version: 1,
percentage: 10,
id: 2
}]
So, as you can see, there are two objects in the list that have the amenity "Pool", how can I break this list into smaller lists based on amenity:
For example:
vlist_a = [{
amenity: "Parking",
amount: 120,
version: 1,
percentage: 4,
id: 1
}]
list_b = [{
amenity: "Pool",
amount: 300,
version: 2,
percentage: 10,
id: 5,
},
{
amenity: "Pool",
amount: 200,
version: 1,
percentage: 10,
id: 2
}]
My intention is that when I order them in that way I can get the object with the greatest version per list using a lambda equation.
Thanks in advance
Use a dictionary for a variable number of variables
The Pythonic solution is to use collections.defaultdict:
from collections import defaultdict
d = defaultdict(list)
for item in original_list:
d[item['amenity']].append(item)
print(d['Pool'])
[{'amenity': 'Pool', 'amount': 300, 'id': 5, 'percentage': 10, 'version': 2},
{'amenity': 'Pool', 'amount': 200, 'id': 2, 'percentage': 10, 'version': 1}]
print(d['Parking'])
[{'amenity': 'Parking', 'amount': 120, 'version': 1, 'percentage': 4, 'id': 1}]
My intention is that when I order them in that way I can get the object with the greatest version per list using a lambda equation.
You can use a dictionary comprehension with max for this task:
res = {k: max(v, key=lambda x: x['version']) for k, v in d.items()}
{'Parking': {'amenity': 'Parking',
'amount': 120,
'id': 1,
'percentage': 4,
'version': 1},
'Pool': {'amenity': 'Pool',
'amount': 300,
'id': 5,
'percentage': 10,
'version': 2}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With