0

Possible Duplicate:
In what case would I use a tuple as a dictionary key?

One of the advantage of tuples is that they can be used as dictionary keys in opposite to lists, as tuples are immutable and lists are mutable.

I haven't seen a useful and real example where tuples are used as dictionary keys. Could you show one or a few useful examples with smart usage of tuples as dictionary keys?

EDIT: In many cases the resulting data structure can be implemented as a class instead of as dictionary with keys as tuples. Explain why in your example is it better to use dictionary instead of a class.

Community
  • 1
  • 1
xralf
  • 3,312
  • 45
  • 129
  • 200

3 Answers3

3

For example, you need a dictionary for employee's, In real world, 2 names (first and last name can be same) (i.e. 2 persons with same name) but combination of names (first and last) with phone no's can't be same. In such a scenario, tuple as a key is required.

avasal
  • 14,350
  • 4
  • 31
  • 47
3

You have a set of points in a 2D/3D space with properties:

shape = {(2,3,4) : {'visible' : False, 'color': 'red'},
         (1,0,2) : {'visible' : True, 'color': 'blue'},
         (1,2,4) : {'visible' : True, 'color': 'green'}}

or you have a custom dictbased relational database with e.g. a primary key based on two rows:

bill_db = {('customer_a', 'date') : bill_properties,
           ... }
Don Question
  • 11,227
  • 5
  • 36
  • 54
1

I think you can use a tuple to define a cell in a chessboard:

cell_1 = (1, 3)
cell_2 = (2, 5)
occupied_cells = {cell_1: True, cell_2: False}

def cell_is_occupied(cell):
    return occupied_cells.get(cell, False)
Griffosx
  • 1,605
  • 1
  • 16
  • 23