Python 如何一次迭代两个字典并使用两者的值和键获得结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20736709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:07:21  来源:igfitidea点击:

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

pythonloops

提问by arisonu123

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 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 forloop. It is because of this that the answers I'm getting are not correct.

以上是我目前的代码。但出于某种原因,它似乎在执行第一个循环,然后是第二个循环,然后是第二个循环,然后是第一个循环,然后是第二个循环。在返回到第一个for循环之前,它似乎每次到达它都会执行第二个循环。正因为如此,我得到的答案是不正确的。

采纳答案by aIKid

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.

但是,请注意字典中的键不是有序的。此外,如果两个字典包含的键数不相同,则上面的代码将失败。

回答by Abhijit

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

看看您的问题,我建议您创建生成器表达式,成对导航两个字典,并使用max和自定义键来计算要评估的销售价格expected_sale_price和相应的库存

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)

回答by user2699

The question isn't well defined, and the answer accepted will fail for some dictionaries. It relies on key ordering, which isn't guaranteed. Adding additional keys to a dictionary, removing keys, or even the order they are added can affect the ordering.

这个问题没有明确定义,对于某些词典,接受的答案将失败。它依赖于无法保证的键排序。向字典中添加额外的键、删除键,甚至是添加的顺序都会影响排序。

A safer solution is to choose one dictionary, din this case, to get the keys from, then use those to access the second dictionary:

更安全的解决方案是选择一个字典,d在这种情况下,从中获取键,然后使用它们访问第二个字典:

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 isn't more complex than the other answers, and is explicit about which keys are being accessed. If the dictionaries have different key orderings, say d2 = {'x': 3, 'b':7, 'c': 3, 'a':9}, consistent results are still given.

这并不比其他答案更复杂,并且明确说明正在访问哪些键。如果字典有不同的键顺序,比如d2 = {'x': 3, 'b':7, 'c': 3, 'a':9},仍然给出一致的结果。