Python 检查字典中的元组值

Python 检查字典中的元组值,python,tuples,dictating,Python,Tuples,Dictating,我有一个字典,它的键是tuple,值也是tuple。我需要一种基于字典键访问字典值的方法。 例如: d = {} d = { (1, 2) : ('A', 'B'),(3, 4) : ('C', 'B') } 现在,首先我需要检查字典中是否已经存在键(1,2) 比如: if d.has_key(1,2) print d[1] print d[2] 就像你在其他任何时候一样使用字典 potential_key = (1,2) potential_val = d.get(potent

我有一个字典,它的键是tuple,值也是tuple。我需要一种基于字典键访问字典值的方法。 例如:

d = {}
d = { (1, 2) : ('A', 'B'),(3, 4) : ('C', 'B') }
现在,首先我需要检查字典中是否已经存在键
(1,2)

比如:

if d.has_key(1,2)
   print d[1]
   print d[2]

就像你在其他任何时候一样使用字典

potential_key = (1,2)
potential_val = d.get(potential_key)
if potential_val is not None:
    # potential_val[0] = 'A'
    # potential_val[1] = 'B'

您可以简单地使用文字元组作为键:

>>> d = {(1, 2): ('A', 'B'), (3, 4): ('C', 'D')}
>>> (1, 2) in d
True
>>> d[(1, 2)]
('A', 'B')
>>> d[(1, 2)][0]
'A'

问题是
f(a,b)
被视为“用两个参数调用f”,因为paren和逗号作为函数调用语法的一部分使用,没有留下任何看起来像元组的东西。如果必须向函数传递文本元组,请使用
f((a,b))

但是由于不推荐使用
dict.has_键
,只需在中使用
,这种不便就消失了:
(1,2)在d中