Использование pydantic для чтения json-данных + универсальная сортировка по имени поля
from copy import deepcopy
from typing import Any, List, Optional
from pydantic import BaseModel, RootModel
class PosaModel(BaseModel):
id: int = None
count: float = None
amount: float = None
class CostModel(BaseModel):
id: Optional[int] = None
name: str = None
number: str = None
ext: str = None
type: str = None
posa: Optional[List[PosaModel]] = None
@property
def fields(self):
return vars(self).keys()
@property
def full_name(self) -> str:
return f"{self.name} - {self.number}"
def __str__(self):
return self.full_name
def __repr__(self):
return self.__str__()
class CostsList(RootModel):
root: List[CostModel] = None
def get_sorted_list_by(
self, field_name: Any, reverse: bool = False
) -> List[CostModel]:
"""
возможные имена для field_name: id, name, number, ext, type
"""
costs = deepcopy(self.root)
fields_list = [getattr(account, field_name) for account in costs]
fields_list.sort(reverse=reverse)
costs_sorted = []
for field in fields_list:
cost = next(filter(
lambda a: getattr(a, field_name) == field, costs
))
costs_sorted.append(cost)
del cost
return costs_sorted
list_dict = [
{"id": 1, "name": "Name 1", "number": "№ 1", "ext": "ext 1", "type": "costa",
"posa":
[{"id": 11, "count": 1.11, "amount": 11.11},
{"id": 12, "count": 1.12, "amount": 12.12}]
},
{"id": 3, "name": "Name 3", "number": "№ 3", "ext": "ext 3", "type": "costa",
"posa":
[{"id": 31, "count": 3.11, "amount": 31.11},
{"id": 32, "count": 3.12, "amount": 32.12}]
},
{"id": 2, "name": "Name 22", "number": "№ 22", "ext": "ext 2", "type": "costa",
"posa":
[{"id": 21, "count": 2.11, "amount": 21.11},
{"id": 22, "count": 2.12, "amount": 22.12}]
}
]
if __name__ == '__main__':
di = list_dict[1]
costs = CostsList().model_validate(list_dict)
print(costs.root)
costs_sort = costs.get_sorted_list_by("name")
print(costs_sort)