1
def getValue(d, key):
    for k, v in d.iteritems():
        print "{0} == {1}".format(k, key)
        if k == key:
            return v
        elif isinstance(v, dict):
            getValue(v, key)
    logging.error("Cannot find key in dictionary")
    return ""

#d = getting the dictionary

getValue(d, "error_frames")

From the print statement I inserted in the function, I clearly see "error_frames == error_frames" appear in the console, but the if statement is not getting executed. Why? The dictionary is constructed by parsing xml with the module xmltodict.

1
  • 2
    Try printing repr(k) and repr(key) instead of using str.format. Commented May 29, 2012 at 14:16

2 Answers 2

12

.format calls the __str__ method of the object and its output can be identical for different objects.

In [1]: a = 1

In [2]: b = '1'

In [3]: print '{0} == {1}'.format(a, b)
1 == 1

In [4]: a == b
Out[4]: False
Sign up to request clarification or add additional context in comments.

1 Comment

I think that what you mean is that .format calls __str__ -- In this case, print is calling __str__ on a string object, which just returns a string.
6

Perhaps the print statement is being executed from a nested recursive call.

    elif isinstance(v, dict):
        getValue(v, key)

Should that be return getValue(key)?

1 Comment

Good catch (+1) : my gut feeling is that this will solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.