3

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]
Nima Soroush
  • 12,242
  • 4
  • 52
  • 53
Rohita Khatiwada
  • 2,835
  • 9
  • 40
  • 52

3 Answers3

7

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'
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
2

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

0

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'
Josh Smeaton
  • 47,939
  • 24
  • 129
  • 164