John Montague
John Montague

Reputation: 2010

Defining a dict with a tuple singleton key

To define a singleton in python use singleton = ('singleton'), A Python dictionary can use a tuple as a key, as in

[('one', 'two'): 5]

But is it possible to do

[('singleton'),: 5]

Somehow?

Upvotes: 0

Views: 415

Answers (2)

hexparrot
hexparrot

Reputation: 3417

Signify to python that 'singleton' is a tuple to make it work:

>>> a = {}
>>> a[('singleton',)] = 5
>>> a
{('singleton',): 5}

Upvotes: 2

EML
EML

Reputation: 455

Yes, you can do this — but not with ('Singleton'). You've got to use ('Singleton',).

The reason for this is that Python will interpret single parentheses around a single item as merely the item itself. Adding a comma enforces the tuple interpretation.

>>> d = {}
>>> d[('Thing')] = "one"
>>> d.keys()
['Thing']
>>> d[('Thing',)] = "another"
>>> d
{'Thing': 'one', ('Thing',): 'another'}

Upvotes: 3

Related Questions