Home > database >  What is the problem with dictionary while using tuple as a key?
What is the problem with dictionary while using tuple as a key?

Time:02-23

I have created a simple dictionary in which tuples are keys

a = {(1, 2): 1, (2, 3): 2}

These both are giving the same results :

print(a[1, 2])
print(a[(1, 2)])

The result is 1.

why?

CodePudding user response:

1, 2 and (1, 2) are both tuples. You can confirm this yourself:

a = 1, 2
b = (1, 2)
print(type(a))  # <class 'tuple'>
print(type(b))  # <class 'tuple'>

As a result, a[1, 2] and a[(1, 2)] are equivalent.

You only need parenthesis around elements of a tuple in certain contexts where the syntax could be ambiguous. For example when passing function args: f(1, 2) passes two arguments to f, but f((1, 2)) passes a single two-item tuple to f.

In all other contexts where there is no ambiguity, the parentheses around the tuple can be omitted. Dictionary lookup is one such context.

  • Related