我有兩個字典:
AvailConcertSeats = {"The Weeknd": 80000, "Maroon 5": 80000, "Justin Bieber": 80000, "Post Malone": 34000}
AvgConcertPrice = {"The Weeknd": 200, "Maroon 5": 109, "Justin Bieber": 250, "Post Malone": 179}
我想列印出AvailConcertSeats值 xAvgConcertPrice值的乘積。
我試過的代碼:
AvailConcertSeats.values() * AvgConcertPrice.values()
uj5u.com熱心網友回復:
您可以使用 dict 理解:
AvailConcertSeats = {"The Weeknd": 80000, "Maroon 5": 80000, "Justin Bieber": 80000, "Post Malone": 34000}
AvgConcertPrice = {"The Weeknd": 200, "Maroon 5": 109, "Justin Bieber": 250, "Post Malone": 179}
output = {k: seats * AvgConcertPrice[k] for k, seats in AvailConcertSeats.items()}
print(output)
# {'The Weeknd': 16000000, 'Maroon 5': 8720000, 'Justin Bieber': 20000000, 'Post Malone': 6086000}
如果你想“安全”(當兩個字典的鍵可能不相同時),以下只會計算它們的交集:
output = {k: AvailConcertSeats[k] * AvgConcertPrice[k] for k in AvailConcertSeats.keys() & AvgConcertPrice.keys()}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492681.html
下一篇:如何反轉字典中鍵的值?
