How to iterate over two dictionaries at once and get the result using values โ€‹โ€‹and keys from both

def GetSale():#calculates expected sale value and returns info on the stock with highest expected sale value global Prices global Exposure global cprice global bprice global risk global shares global current_highest_sale best_stock=' ' for value in Prices.values(): cprice=value[1] bprice=value[0] for keys, values in Exposure.items(): risk=values[0] shares=values[1] Expected_sale_value=( (cprice - bprice ) - risk * cprice) * shares print (Expected_sale_value) if current_highest_sale < Expected_sale_value: current_highest_sale=Expected_sale_value best_stock=Exposure[keys] return best_stock +" has the highest expected sale value" 

Above is my code now. For some reason, however, it seems to be doing the first cycle, then the second, then the second, then the first, then the second. It seems like he does a second loop every time he gets to him before returning to the first for loop. Because of this, the answers that I get are incorrect.

+12
source share
3 answers

The question is a bit vague, but answering the headline, you can get both keys and values โ€‹โ€‹at the same time, for example like this:

 >>> d = {'a':5, 'b':6, 'c': 3} >>> d2 = {'a':6, 'b':7, 'c': 3} >>> for (k,v), (k2,v2) in zip(d.items(), d2.items()): print k, v print k2, v2 a 5 a 6 c 3 c 3 b 6 b 7 

However, note that the keys in the dictionaries are not ordered. In addition, if two dictionaries do not contain the same number of keys, the above code will fail.

+36
source

The question is not completely defined, and the accepted answer will fail for some dictionaries. He relies on ordering keys, which is not guaranteed. Adding additional keys to the dictionary, deleting keys, or even adding an order can affect the order.

A safer solution is to select one dictionary, d in this case, to get the keys, and then use them to access the second dictionary:

 d = {'a':5, 'b':6, 'c': 3} d2 = {'a':6, 'b':7, 'c': 3} [(k, d2[k], v) for k, v in d.items()] 

Result:

 [('b', 7, 6), ('a', 6, 5), ('c', 3, 3)] 

This is no more complicated than the other answers, and it is clear which keys are available. If the dictionaries have different key orders, say d2 = {'x': 3, 'b':7, 'c': 3, 'a':9} , you will still get consistent results.

+7
source

Looking at your problem, I suggest you create a generator expression that moves two dictionaries in pairs and using max with a custom key to calculate the selling price to estimate expected_sale_price and the corresponding stock

Data examples

 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)))) 

Code example

 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) 
-1
source

All Articles