如何一次迭代两个字典并使用两个字典中的值和键来获得结果 [英] How to iterate over two dictionaries at once and get a 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"
以上是我当前的代码.但是由于某种原因,它似乎正在执行第一个循环,然后执行第二个循环,然后执行第二个循环,然后执行第一个循环,然后执行第二个循环.似乎每次到达它都会执行第二个循环,然后再回到第一个for
循环.因此,我得到的答案不正确.
Above is my code currently. For some reason though, it appears to be doing the first loop, then the second, then the second, then the first, then the second. It appears to do the second loop each time it gets to it before going back to the first for
loop. It is because of this that the answers I'm getting are not correct.
推荐答案
这个问题有点含糊,但是回答标题,您可以像这样同时获取键和值:
The question is a bit vague, but answering the title, you can get both keys and values at the same time 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, do mind that keys in dictionaries aren't ordered. Furthermore, if the two dictionaries do not contain the same number of keys, the code above will fail.
这篇关于如何一次迭代两个字典并使用两个字典中的值和键来获得结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!