Saya memiliki array yang terlihat seperti ini comp_data = [{"produk_id": 432263, "price_zone_id": 1, "oreilly_price": 0, "..." ...

0
newbieprogrammer095 5 April 2021, 21:50

1 menjawab

Kode Anda membuat "harga" dan "indeks" alih-alih seluruh nama. Mana yang kamu inginkan?

comp_data = [
  {
    "product_id": 432263,
    "price_zone_id": 1,
    "oreilly_price": 0,
    "amazon_price": 0,
    "az_price": 0,
    "rockauto_price": 0,
    "napa_price": 0,
    "oreilly_index": 0,
    "amazon_index": 0,
    "az_index": 0,
    "rockauto_index": 0,
    "napa_index": 0,
    "weighted_comp_price": 0,
    "weighted_comp_index": 0,
    "week": None
  }
]

stores = {}
for data in comp_data:
    for key,value in data.items():
        if key not in ('product_id','price_zone_id','week'):
            words = key.split('_')
            store_name ='_'.join(words[:-1])
            value_type = words[-1]
            if store_name not in stores:
                stores[store_name] = {'name': store_name.title()}
            stores[store_name][key] = value

from pprint import pprint
pprint(stores)

Keluaran:

{'amazon': {'amazon_index': 0, 'amazon_price': 0, 'name': 'Amazon'},
 'az': {'az_index': 0, 'az_price': 0, 'name': 'Az'},
 'napa': {'name': 'Napa', 'napa_index': 0, 'napa_price': 0},
 'oreilly': {'name': 'Oreilly', 'oreilly_index': 0, 'oreilly_price': 0},
 'rockauto': {'name': 'Rockauto', 'rockauto_index': 0, 'rockauto_price': 0},
 'weighted_comp': {'name': 'Weighted_Comp',
                   'weighted_comp_index': 0,
                   'weighted_comp_price': 0}}
0
Tim Roberts 5 April 2021, 18:59