Defining a dict with a tuple singleton key

Go To StackoverFlow.com

0

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?

2012-04-03 23:24
by John Montague


3

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'}
2012-04-03 23:28
by EML


2

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

>>> a = {}
>>> a[('singleton',)] = 5
>>> a
{('singleton',): 5}
2012-04-03 23:28
by hexparrot
Ads