python сортировать список словаря по списку элементов

#python

#питон #python

Вопрос:

     sellers = ["amazon", "walmart", "Target", "CVS",  "Walgreens", "macys", "kohls"]

    data = [
        {
        "price": "21",
        "title": "Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl",
        "seller": "kohls",
        },
        {
        "price": "21.00",
        "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
        "seller": "amazon"
        },
        {
            "price": "21.00",
            "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
            "seller": "macys"
        },
        {
            "price": "21.00",
            "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
            "seller": "walmart"
        }
    ]
  

Вот мои данные. Я хочу отсортировать свои данные по продавцу в соответствии с приведенным выше списком.
На самом деле список должен быть динамичным.

Пожалуйста, взгляните, как я могу этого добиться.

Ниже приведен мой

ожидаемый результат:

     [
        {
            "price": "21.00",
            "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
            "seller": "amazon"
        },
        {
            "price": "21.00",
            "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
            "seller": "walmart"
        },
        {
            "price": "21.00",
            "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
            "seller": "macys"
        },
        {
        "price": "21",
        "title": "Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl",
        "seller": "kohls",
        }
    ]
  

Пожалуйста, взгляните

Ответ №1:

Вы можете использовать sorted()

 res = sorted(data, key=lambda x: sellers.index(x['seller']))

print(res)
  

Вывод:

 [{'price': '21.00',
  'title': 'Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream',
  'seller': 'amazon'},
 {'price': '21.00',
  'title': 'Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream',
  'seller': 'walmart'},
 {'price': '21.00',
  'title': 'Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream',
  'seller': 'macys'},
 {'price': '21',
  'title': 'Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl',
  'seller': 'kohls'}]