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

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

    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, d in this case, to get the keys from, then use those 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 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.

提交回复
热议问题