Muadh Ghuneim Muadh Ghuneim - 8 months ago 79
Python Question

Python's if key in dictionary not working correctly

I'm working on a programming problem where user input can define variables, like so:

length = 1

When the user does this, I store the pair in a dictionary:

{'length': '1'}

The problem is, when I later try to check if a key exists in the dictionary, I always get False, even if it is definitely in there. Here is my code:

import math

def main():
curr_formula = input()
substitutions = dict()

while(curr_formula != "0"):
if("=" in curr_formula):
split_formula = curr_formula.split("=")
substitutions[split_formula[0]] = split_formula[1]

curr_split = curr_formula.split(" ")
for i in range(len(curr_split)):

# this if statement never runs for some reason
if(curr_split[i] in substitutions):
curr_split[i] = substitutions[curr_split[i]]


curr_formula = input()

The input "length = 1" and then "length + 2" should print "1 + 2" but instead cannot detect that the key already exists. Any insight on this issue would be much appreciated!

Answer Source

When you split on '=', there is a space after the first term and before the second.

>>> 'length = 1'.split('=')
['length ', ' 1']

Whereas when you split on ' ' it's removed.

>>> 'length = 1'.split(' ')
['length', '=', '1']

As a result, the keys in your dict are probably different.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download