Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split a list of objects into sublists based on objects attributes

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

like image 338
Stephen-Njoroge Avatar asked May 16 '26 13:05

Stephen-Njoroge


1 Answers

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}}
like image 145
jpp Avatar answered May 18 '26 03:05

jpp