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

前端 未结 3 509
余生分开走
余生分开走 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:47

    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.

提交回复
热议问题