본문 바로가기
파이썬

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

by º기록 2020. 12. 27.
반응형
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 루프로 돌아 가기 전에 도달 할 때마다 두 번째 루프를 수행하는 것처럼 보입니다. 이 때문에 제가받는 답이 정확하지 않습니다.

 

해결 방법

 

질문은 약간 모호하지만 제목에 답하면 다음과 같이 키와 값을 동시에 얻을 수 있습니다.

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

그러나 사전의 키는 정렬되지 않습니다. 또한 두 사전에 동일한 수의 키가 포함되어 있지 않으면 위 코드가 실패합니다.

 

참조 페이지 https://stackoverflow.com/questions/20736709

 

 

반응형

댓글