How to iterate over two dictionaries at once and get a result using values and keys from both

前端 未结 3 511
余生分开走
余生分开走 2021-01-31 20:25
def GetSale():#calculates expected sale value and returns info on the stock with              highest expected sale value
      global Prices
      global Exposure
              


        
3条回答
  •  迷失自我
    2021-01-31 20:48

    Looking at your problem, I would suggest you to create generator expression that navigates the two dictionary in pairs and using max with a custom key to calculate sale price to evaluate expected_sale_price and the corresponding stock

    Sample Data

    Prices = dict(zip(range(10), ((randint(1,100), randint(1,100)) for _ in range(10))))
    Exposure = dict(zip(range(10), ((randint(1,100), randint(1,100)) for _ in range(10))))
    

    Sample Code

    def GetSale(Prices, Exposure):
        '''Get Sale does not need any globals if you pass the necessary variables as
           parameteres
        '''
        from itertools import izip
        def sale_price(args):
            '''
            Custom Key, used with the max function
            '''
            key, (bprice, cprice), (risk, shares) = args
            return ( (cprice - bprice ) - risk * cprice) * shares
    
        #Generator Function to traverse the dict in pairs
        #Each item is of the format (key, (bprice, cprice), (risk, shares))
        Price_Exposure = izip(Prices.keys(), Prices.values(), Exposure.values())
    
    
        #Expected sale price using `max` with custom key
        expected_sale_price = max(Price_Exposure, key = sale_price)
        key, (bprice, cprice), (risk, shares) =  expected_sale_price
        #The best stock is the key in the expected_sale_Price
        return "Stock {} with values bprice={}, cprice = {}, risk={} and shares={} has the highest expected sale value".format(key, bprice, cprice, risk, shares)
    

提交回复
热议问题