字典列表中的组对象

时间:2018-01-24 07:46:47

标签: python json dictionary

我不确定如何清楚地解释这一点,但我有一个来自API的JSON结果,该结果返回未知数量的产品,每个产品及其价格分别针对3种不同的服务。

然后我需要接受这些组并迭代它们作为一个组处理它们。

例如数据集。

[
  { 'name': 'widgetb', 'type': 'ebay' }
  { 'name': 'widgeta', 'type': 'amazon' }
  { 'name': 'widgetc', 'type': 'newegg' }
  { 'name': 'widgeta', 'type': 'newegg' }
  { 'name': 'widgetb', 'type': 'newegg' }
  { 'name': 'widgeta', 'type': 'ebay' }
  { 'name': 'widgetc', 'type': 'amazon' }
  { 'name': 'widgetb', 'type': 'amazon' }
  { 'name': 'widgetc', 'type': 'ebay' }
]

有两个API结果集,第一个为您提供可用产品的列表,以及与服务配对的唯一条目(Amazon,eBay,Newegg)。因此,对于每个产品,有3个条目,但它们不会有序。

第二个API返回产品服务&价钱。 示例价格结果将是。

[
    ProductC-NewEgg: Price
    ProdutA-NewEgg: Price
    ProductB-NewEgg: Price
    ProductA-Amazon: Price
    ProductA-Ebay: Price
    ProductC-Amazon: Price
    ProductB-Ebay: Price
    ProductC-Ebay: Price
    ProductB-Amazon: Price
]

我最初的想法是获取第一个API中所有产品的唯一列表,并将它们放入列表中。然后浏览产品/服务的每个组合,并填写存储在每个产品列表元素下的字典。

所以结果会像>

[
Product A { price a, b c }
Product B { price a, b c }
Product C { price a, b c }
]

我觉得我接近错了。

1 个答案:

答案 0 :(得分:0)

不确定我是否明白您的要求。但请查看:

>>> first_api_result = [
  { 'name': 'widgetb', 'type': 'ebay' }
  ,{ 'name': 'widgeta', 'type': 'amazon' }
  ,{ 'name': 'widgetc', 'type': 'newegg' }
  ,{ 'name': 'widgeta', 'type': 'newegg' }
  ,{ 'name': 'widgetb', 'type': 'newegg' }
  ,{ 'name': 'widgeta', 'type': 'ebay' }
  ,{ 'name': 'widgetc', 'type': 'amazon' }
  ,{ 'name': 'widgetb', 'type': 'amazon' }
  ,{ 'name': 'widgetc', 'type': 'ebay' }
]
>>> second_api_result=[
    {'widgeta-NewEgg': 10 }
    ,{'widgetb-NewEgg': 20  }
    ,{'widgetc-NewEgg': 30 }
    ,{'widgetb-Amazon': 35 }
    ,{'widgetb-Ebay': 40   }
    ,{'widgeta-Amazon': 50 }
    ,{'widgetc-Ebay': 60   }
    ,{'widgeta-Ebay': 70   }
    ,{'widgetc-Amazon': 80 }
]
>>> result = {d['name']:[]for d in first_api_result}
>>> for price_dict in second_api_result:
        product,price = price_dict.items()[0]
        result[product[:product.index('-')]].append(price)


>>> result
{'widgetc': [30, 60, 80], 'widgetb': [20, 35, 40], 'widgeta': [10, 50, 70]}
相关问题