I have a python script where I’ve printed the value of two variables. These are dash callback id’s. An excerpt is:
ctx = dash.callback_context changed_id = [p['prop_id'] for p in ctx.triggered][0] order_id = changed_id.split('.')[0] print(child['props']['id']) print(order_id) print(child['props']['id'] ==order_id)
The output is:
{'type': 'dynamic-order', 'index': 3} {"index":3,"type":"dynamic-order"} False
But when I copy and past the output of the first two lines and run them directly into the python3 interpreter I get:
>>> {'type': 'dynamic-order', 'index': 3}=={"index":3,"type":"dynamic-order"} True
I would expect these should both return the same boolean value. How is it these values are different? Furthermore, why am I getting False in the script and how can I change it so that it evaluates to True?
Advertisement
Answer
It looks like order_id
is actually a string. If it were a dict, Python would use single-quotes there instead of double-quotes, and put spaces after the colons :
and commas ,
.
It seems to contain JSON, so use the json
module to parse it.
import json order_id = '{"index":3,"type":"dynamic-order"}' d = {'type': 'dynamic-order', 'index': 3} print(json.loads(order_id) == d) # -> True
In the future, you can use repr()
or pprint.pprint()
to diagnose issues like this.
print(repr(order_id)) # -> '{"index":3,"type":"dynamic-order"}' print(repr(d)) # -> {'type': 'dynamic-order', 'index': 3}
from pprint import pprint pprint(order_id) # -> '{"index":3,"type":"dynamic-order"}' pprint(d) # -> {'index': 3, 'type': 'dynamic-order'} pprint(d, sort_dicts=False) # -> {'type': 'dynamic-order', 'index': 3}
(Note that pprint.pprint()
sorts dict keys by default, which is less useful as of Python 3.7.)