为什么同样的表达式 return 在作为一行输入 python 解释器时为真,而在脚本中 运行 时为假?
Why does this same expression return True in when entered as a line into the python interpreter and False when run in a script?
我有一个 python 脚本,我在其中打印了两个变量的值。这些是破折号回调 ID。摘录如下:
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)
输出为:
{'type': 'dynamic-order', 'index': 3}
{"index":3,"type":"dynamic-order"}
False
但是,当我复制并粘贴前两行的输出并 运行 它们直接进入 python3 解释器时,我得到:
>>> {'type': 'dynamic-order', 'index': 3}=={"index":3,"type":"dynamic-order"}
True
我希望它们 return 具有相同的布尔值。这些值有何不同?此外,为什么我在脚本中得到 False 以及如何更改它以使其计算为 True?
看起来order_id
实际上是一个字符串。如果它是一个字典,Python 将在那里使用单引号而不是双引号,并在冒号 :
和逗号 ,
.
之后放置空格
好像包含JSON,所以用json
模块解析
import json
order_id = '{"index":3,"type":"dynamic-order"}'
d = {'type': 'dynamic-order', 'index': 3}
print(json.loads(order_id) == d) # -> True
以后,您可以使用repr()
or pprint.pprint()
来诊断此类问题。
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}
(注意pprint.pprint()
默认对dict键进行排序,用处不大。)
我有一个 python 脚本,我在其中打印了两个变量的值。这些是破折号回调 ID。摘录如下:
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)
输出为:
{'type': 'dynamic-order', 'index': 3}
{"index":3,"type":"dynamic-order"}
False
但是,当我复制并粘贴前两行的输出并 运行 它们直接进入 python3 解释器时,我得到:
>>> {'type': 'dynamic-order', 'index': 3}=={"index":3,"type":"dynamic-order"}
True
我希望它们 return 具有相同的布尔值。这些值有何不同?此外,为什么我在脚本中得到 False 以及如何更改它以使其计算为 True?
看起来order_id
实际上是一个字符串。如果它是一个字典,Python 将在那里使用单引号而不是双引号,并在冒号 :
和逗号 ,
.
好像包含JSON,所以用json
模块解析
import json
order_id = '{"index":3,"type":"dynamic-order"}'
d = {'type': 'dynamic-order', 'index': 3}
print(json.loads(order_id) == d) # -> True
以后,您可以使用repr()
or pprint.pprint()
来诊断此类问题。
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}
(注意pprint.pprint()
默认对dict键进行排序,用处不大