1

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?

DrRaspberry
  • 367
  • 2
  • 13
  • What type is `child['props']['id']`? An `OrderedDict` for example, uses the key order in comparing two types, while `dict` does not. – chepner May 11 '21 at 19:57
  • 5
    I think `order_id` is a string. A dict representation would show single quotes instead of double quotes. – khelwood May 11 '21 at 19:58
  • You're right. Thanks! – DrRaspberry May 11 '21 at 19:59
  • @khelwood: The spacing is also a giveaway; Python `dict` `repr`s always put a space after the `:`s. You can see the type distinction clearly by replacing `print(order_id)` with `print(repr(order_id))` which wouldn't change for a `dict`, but would show the outer string quotes for a `str`. – ShadowRanger May 11 '21 at 20:11

1 Answers1

0

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.)

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Thanks. That solves it. I've also noticed you can import ast and use ast.literal_eval(order_id) – DrRaspberry May 11 '21 at 20:34
  • @DrRaspberry Definitely. I only think it's JSON cause it's using double-quotes instead of single-quotes. But on the other hand, I'm not familiar with Dash so I don't really know. – wjandrea May 11 '21 at 20:39