2011-04-10 62 views
2

我有一个字典,其中元组作为其键和元组作为其值。我需要一种方法来根据其键来访问字典的值。 例如:检查字典中的元组值

d = {} 
d = { (1, 2) : ('A', 'B'),(3, 4) : ('C', 'B') } 

现在,首先我需要检查,如果键(1, 2)在字典中已经存在。

喜欢的东西:

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

回答

4

你可以简单地使用文字作为元组的关键:

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

只需使用字典,你会在其他任何时间......

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

问题在于f(a, b)被视为“带有两个参数的调用f”,因为parens和逗号是consu med作为函数调用语法的一部分,不会看起来像一个元组。如果您必须将文字元组传递给函数,请使用f((a, b))

但由于dict.has_key已被弃用,只是使用in,这不便消失:(1, 2) in d