Rel*_*der 2 python dictionary python-3.x
>>> data = "0:1:2"
>>> h2 = data[0]
>>> a = {0: "... ", 1: "..- ", 2: ".-."}
>>> print (0 in a)
True
>>> print (h2)
0
>>> print (h2 in a)
False
>>> print (a.keys())
dict_keys([0, 1, 2])
Run Code Online (Sandbox Code Playgroud)
别名出了什么问题?
h2是一个字符串值,但您的字典键是整数.整数和字符串cotaining只有数字打印相同的,但不是相同的类型和不同的JavaScript,Python不认为他们等于或整数和字符串之间强求.
首先将字符串显式转换为整数:
>>> type(h2)
<class 'str'>
>>> type(next(a)) # first key in a
<class 'int'>
>>> int(h2) in a
True
>>> a[int(h2)]
'... '
Run Code Online (Sandbox Code Playgroud)
要正确查看不同类型之间的差异,请repr()在打印时使用:
>>> print(repr(h2))
'0'
>>> print(repr(0))
0
Run Code Online (Sandbox Code Playgroud)
请注意字符串值周围的引号.Python交互式shell repr()在回显值时默认使用(除了None回显之外的所有内容):
>>> 'a string value'
'a string value'
>>> 42
42
Run Code Online (Sandbox Code Playgroud)