0

So I'm new to Python, and was trying to generate the following dictionary comprehensions from the two lists.

top5shows = ['Soldier','The Run', 'Metachomas','The Average Lad','James Eathersen']
budget =  [200, 110, 34, 2, 0.5]
revenue = [220,190, 80, 2.3, 1]


profit_dict = {show: (((rev - bud) / bud) * 100) for show in top5shows for rev in revenue for bud in budget}`

The idea is to produce a dictionary with the name of the movie as the key, and it's percentage of profit as the value. However, the result is giving me the same value for all the keys, which is the profit percentage of the last movie in the list.

Result:

{'Soldier': 100.0, 'The Run': 100.0, 'Metachomas': 100.0, 'The Average Lad': 100.0, 'James Eathersen': 100.0}
  • But where am I providing duplicate keys to the dictionary? – TheFutureNav Jul 25 '19 at 10:04
  • You have three nested `for` loops - i.e. you are iterating over every possible pair of `(budget, revenue)` for each top show; you probably wanted to iterate over the three lists in *parallel*. – meowgoesthedog Jul 25 '19 at 10:04
  • Oh yes probably! How can one do that in a dictionary comprehension? Or can one do that in a dict comp at all? – TheFutureNav Jul 25 '19 at 10:05

2 Answers2

1

You don't need to make a triple for loops inside dictionary comprehensions

profit_dict = {show: (((revenue[i] - budget[i]) / budget[i]) * 100) for i, show in enumerate(top5shows)}
print(profit_dict) # {'Soldier': 10.0, 'The Run': 72.72727272727273, 'Metachomas': 135.29411764705884, 'The Average Lad': 14.999999999999991, 'James Eathersen': 100.0}
0

Assuming you want to iterate the lists in parallel not nested (as does your code), a working solution would look like this:

profit_dict = {show: (((revenue[idx] - budget[idx]) / budget[idx]) * 100) for idx, show in enumerate(top5shows)}
Done Data Solutions
  • 2,156
  • 19
  • 32