Home > Software design >  Python, adding two values from two different dictionaries in a for loop if conditions are satisfied
Python, adding two values from two different dictionaries in a for loop if conditions are satisfied

Time:06-21

I want to know if there is a possible solution for my problem. I want add and return the integers from each dictionary if the string conditions 'Mars' and 'First' are satisfied. My for loop is not working, i need help. the printed value should be 230. Should I import a module or a package?

my code:

'''

   planets = {
  'Mercury':['Estimated travel duration time: 6.5 years','./static/Hohmann_Mercury.gif', 110],
  'Venus':['Estimated travel duration time: 15 months', './static/Hohmann_Venus.gif',90 ], 
  'Mars': ['Estimated travel duration time: 7 months','./static/Hohmann_Mars.gif', 160],
  'Jupiter': ['Estimated travel duration time: 6 years','./static/Hohmann_Jupiter.gif',300],
  'Saturn':['Estimated travel duration time: 7 years','./static/Hohmann_Saturn.gif',515],
  'Uranus':['Estimated travel duration time: 8.5 years','./static/Hohmann_Uranus.gif',800],
  'Neptune':['Estimated travel duration time: 12 years','./static/Hohmann_Neptune.gif',960]}

  prices = {'Economy':20, 'Business': 55, 'First': 70 }


  planet = 'Mars'
  price = "First"

  for i in planets.keys() and prices.keys() :
         if i == planet and i == price:
             sum = planets.get(i)[2]   prices.get(i)[0]
            print(sum)

'''

CodePudding user response:

The purpose of using dictionaries is to avoid looping every time you want to do a lookup. If you want Mars info, ask for it. If you want first class info, ask for it:

planets[planet][2]   prices[price]

Using get will help you here not at all: you'll end up trying to add None and getting a misleading error message instead of a straightforward KeyError that tells you what the problem is.

CodePudding user response:

To me it seems it's as simple as

print(planets[planet][2]   prices[price])

That said, a few questions to hopefully help you understand what's wrong with your code:

  • for i in planets.keys() and prices.keys() : what do you expect this to do?
  • how could possibly i be equal to both price and planet in your second line, since price and planet are different?
  • Related