Checking tuples values in dictionary

7.4k views Asked by At

I have a dictionary having tuple as its key and also tuple as its values. I need a way to access the values of dictionary based on its keys. For example:

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

Now, first I need to check if keys (1, 2) already exists in a dictionary.

Something like:

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

There are 3 answers

0
Frédéric Hamidi On BEST ANSWER

You can simply use a literal tuple as the key:

>>> 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
Josh Smeaton On

Just use the dictionary as you would at any other time...

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

The problem is that f(a, b) is treated as "call f with two arguments" because the parens and commas are consumed as part of the function call syntax, leaving nothing looking like a tuple. Use f((a, b)) if you must pass a literal tuple to a function.

But since dict.has_key is deprecated, just use in, and this inconvenience disappears: (1, 2) in d