Johanna
Johanna

Reputation: 1039

Role of comma when adding a dictionary entry in Python

I have a simple question.

I have a dictionary: table = collections.defaultdict(set), and a previously defined grammar consisting of rules like the following:

Rule(('Noun', ('money',)))
Rule(('Noun', ('book',)))
Rule(('S', ('book',)))

Now, when I type this, nothing happens.

for rule in grammar:
    if rule.symbols == ("book"):
        table[col - 1, col].add(rule.head)

When I type this, the entry is added.

for rule in grammar:
    if rule.symbols == ("book",):
        table[col - 1, col].add(rule.head)

The only difference between the two is the comma behind "book". What does this comma do and why is it necessary?

Upvotes: 3

Views: 938

Answers (4)

Antwane
Antwane

Reputation: 22598

The comma transform the expression type from str (with useless parenthesis around) to tuple with single element.

Use type() to see this in action:

>>> type(("book"))
<class 'str'>
>>> type(("book",))
<class 'tuple'>

Upvotes: 0

John Szakmeister
John Szakmeister

Reputation: 47022

In the first case, ("book") the parens are just a way of grouping the expression. The value of that expression is just the string "book".

In the second case, it's creating a tuple, with one element in it.

Upvotes: 4

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

One is string, second is tuple (,):

>>> ("book")
'book'
>>> ("book",)
('book',)

Upvotes: 4

Qiang Jin
Qiang Jin

Reputation: 4467

You need add comma to make it a tuple, otherwise it's just a string.

Upvotes: 4

Related Questions