【问题标题】:Python - Itterate down dictionairy - move down tree conditionallyPython - 向下迭代字典 - 有条件地向下移动树
【发布时间】:2022-01-02 16:45:09
【问题描述】:

我在下面有一些 Python 代码,它沿着树向下走,但我希望它沿着树向下工作,检查有条件地根据值采取一些路径。我想根据条件和fulfillmentChannel获取树分支的fulfillmentChannel

parsed_results['LowestLanded'] = sku_multi_sku['Summary']['LowestPrices']['LowestPrice']['LandedPrice']['Amount']['value']

这会沿着这棵树向下走,但值是因为有两个 LowestPrice 记录/字典为每个 conditionfulfillmentChannel 对返回一个。我想过滤condition=newfulfillmentChannel=Amazon,所以我只取回一条记录。当我解析 XML 数据时,我可以使用类似于 LowestPrices/LowestPrice[@condition='new'][@fulfillmentChannel='Merchant']/LandedPrice/Amount" 的代码来执行此操作,但在这里无法获得类似的代码。我如何用字典做到这一点?

 "LowestPrices":{
     "value":"\n                ",
     "LowestPrice":[
        {
           "value":"\n                    ",
           "condition":{
              "value":"new"               #condtion new
           },
           "fulfillmentChannel":{
              "value":"Amazon"            ## fulfilllmentChannel #1
           },
           "LandedPrice":{
              "value":"\n                        ",
              "CurrencyCode":{
                 "value":"USD"
              },
              "Amount":{
                 "value":"19.57"
              }
           },
           "ListingPrice":{
              "value":"\n                        ",
              "CurrencyCode":{
                 "value":"USD"
              },
              "Amount":{
                 "value":"19.57"
              }
           },
           "Shipping":{
              "value":"\n                        ",
              "CurrencyCode":{
                 "value":"USD"
              },
              "Amount":{
                 "value":"0.00"
              }
           }
        },
        {
           "value":"\n                    ",
           "condition":{
              "value":"new"
           },
           "fulfillmentChannel":{
              "value":"Merchant"
           },
           "LandedPrice":{
              "value":"\n                        ",
              "CurrencyCode":{
                 "value":"USD"
              },
              "Amount":{
                 "value":"19.25"
              }
           },
           "ListingPrice":{
              "value":"\n                        ",
              "CurrencyCode":{
                 "value":"USD"
              },
              "Amount":{
                 "value":"19.25"
              }
           },
           "Shipping":{
              "value":"\n                        ",
              "CurrencyCode":{
                 "value":"USD"
              },
              "Amount":{
                 "value":"0.00"
              }
           }
        }
     ]
  },

【问题讨论】:

  • 这里是否有答案,我只需要在列表中的级别迭代/循环数据?

标签: python json python-3.x list dictionary


【解决方案1】:

您可以将list comprehensions 与条件逻辑一起用于您的目的,如下所示:

my_dict = {
    "LowestPrices": {
        "value": "\n                ",
        "LowestPrice": [{
            "value": "\n                    ",
            "condition": {
                "value": "new"
            },
            "fulfillmentChannel": {
                "value": "Amazon"
            },
            "LandedPrice": {
                "value": "\n                        ",
                "CurrencyCode": {
                    "value": "USD"
                },
                "Amount": {
                    "value": "19.57"
                }
            },
            "ListingPrice": {
                "value": "\n                        ",
                "CurrencyCode": {
                    "value": "USD"
                },
                "Amount": {
                    "value": "19.57"
                }
            },
            "Shipping": {
                "value": "\n                        ",
                "CurrencyCode": {
                    "value": "USD"
                },
                "Amount": {
                    "value": "0.00"
                }
            }
        },
            {
                "value": "\n                    ",
                "condition": {
                    "value": "new"
                },
                "fulfillmentChannel": {
                    "value": "Merchant"
                },
                "LandedPrice": {
                    "value": "\n                        ",
                    "CurrencyCode": {
                        "value": "USD"
                    },
                    "Amount": {
                        "value": "19.25"
                    }
                },
                "ListingPrice": {
                    "value": "\n                        ",
                    "CurrencyCode": {
                        "value": "USD"
                    },
                    "Amount": {
                        "value": "19.25"
                    }
                },
                "Shipping": {
                    "value": "\n                        ",
                    "CurrencyCode": {
                        "value": "USD"
                    },
                    "Amount": {
                        "value": "0.00"
                    }
                }
            }
        ]
    },
}

lowest_prices = [x for x in my_dict["LowestPrices"]["LowestPrice"] if
                 x["condition"]["value"] == "new"
                 and x["fulfillmentChannel"]["value"] == "Amazon"]

lowest_prices 是满足所需条件的所有字典的列表。如果您确定您的案例中只有一本满足条件的字典,或者您只想获取第一本的数量,您只需执行以下操作:

if len(lowest_prices) > 0:
    amount = lowest_prices[0]["LandedPrice"]["Amount"]["value"]
    print(amount)

【讨论】:

    【解决方案2】:

    这个问题的模型方法

    from unittest import TestCase
    from pydantic import BaseModel
    from typing import List
      
    class MdlValue(BaseModel):
        value:str
        
    class MdlFulfillment(BaseModel):
        value:str
      
    class MdlPrice(BaseModel):
        value:str
        CurrencyCode:MdlValue
        Amount:MdlValue
              
    class MdlPrices(BaseModel):
        condition:MdlValue
        fulfillmentChannel:MdlFulfillment
        LandedPrice:MdlPrice
        ListingPrice:MdlPrice
        Shipping:MdlPrice
     
    class MdlPricesList(BaseModel):
            value:str
            LowestPrice:List[MdlPrices]
               
    class MdlLowestPrices(BaseModel):
        LowestPrices:MdlPricesList
        
        
    data =  { 
        "LowestPrices":{
         "value":"\n                ",
         "LowestPrice":[
            {
               "value":"\n                    ",
               "condition":{
                  "value":"new"               #condtion new
               },
               "fulfillmentChannel":{
                  "value":"Amazon"            ## fulfilllmentChannel #1
               },
               "LandedPrice":{
                  "value":"\n                        ",
                  "CurrencyCode":{
                     "value":"USD"
                  },
                  "Amount":{
                     "value":"19.57"
                  }
               },
               "ListingPrice":{
                  "value":"\n                        ",
                  "CurrencyCode":{
                     "value":"USD"
                  },
                  "Amount":{
                     "value":"19.57"
                  }
               },
               "Shipping":{
                  "value":"\n                        ",
                  "CurrencyCode":{
                     "value":"USD"
                  },
                  "Amount":{
                     "value":"0.00"
                  }
               }
            },
            {
               "value":"\n                    ",
               "condition":{
                  "value":"new"
               },
               "fulfillmentChannel":{
                  "value":"Merchant"
               },
               "LandedPrice":{
                  "value":"\n                        ",
                  "CurrencyCode":{
                     "value":"USD"
                  },
                  "Amount":{
                     "value":"19.25"
                  }
               },
               "ListingPrice":{
                  "value":"\n                        ",
                  "CurrencyCode":{
                     "value":"USD"
                  },
                  "Amount":{
                     "value":"19.25"
                  }
               },
               "Shipping":{
                  "value":"\n                        ",
                  "CurrencyCode":{
                     "value":"USD"
                  },
                  "Amount":{
                     "value":"0.00"
                  }
               }
            }
         ]
      }
    }
    
    class TestStackOverflowQuestens(TestCase):
        
        def test_run1(self):
            x = MdlLowestPrices.parse_obj(data)
            for i in x.LowestPrices.LowestPrice:
                   if (i.condition.value == "new" and i.fulfillmentChannel.value == "Amazon"):
                       print(i.ListingPrice.Amount.value) 
    

    【讨论】:

      【解决方案3】:

      这里有几种方法:

      1. 使用filter()
      
      lowest_price = sku_multi_sku['Summary']['LowestPrices']['LowestPrice']
      
      lowest_price_list = list(filter(lambda sku: sku['condition']['value'] == 'new' and sku['fulfillmentChannel']['value'] == 'Amazon'))
      
      # if you are sure that there would be only one item with lowest_price, then
      # CAUTION: One should, however, check for the None type
      print(lowest_price_list[0]['ListingPrice']['Amount']['value']) # Output: 19.57
      
      
      1. 使用List Comprehension
      
      lowest_price = sku_multi_sku['Summary']['LowestPrices']['LowestPrice']
      
      lowest_price_list = [i for i in lowest_price if i['condition']['value'] == 'new' and i['fulfillmentChannel']['value'] == 'Amazon']
      
      print(lowest_price_list[0]['ListingPrice']['Amount']['value'])
      # Output: 19.57 --> With the same cautionary note as above
      
      
      

      注意filter() 转换为 list comprehension

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多