Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
Johanna Avatar asked Jun 16 '26 08:06

Johanna


2 Answers

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.

like image 105
John Szakmeister Avatar answered Jun 17 '26 22:06

John Szakmeister


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

like image 33
Qiang Jin Avatar answered Jun 17 '26 21:06

Qiang Jin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!