Python Forum

Full Version: curious syntax with dictionary item
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
d = {}
a = "hello"
d['x'] = a,
print(d)
Here's the result:

{'x': ('hello',)}

Python created the item as a two-element list maybe?

Consider:

>>> print(d["x"][0])
hello
Do you wonder what element 1 is... I do... anticipation...

IndexError: tuple index out of range Huh
It is the comma at the end of line 3. It creates a tuple, which is the immutable (more static) version of a list. Remove that and the value will just be the string.

You get an index error because the tuple is length 1. The ('hello',) notation is to distinguish it from ('hello'), which just evaluates to 'hello'.
I hear your words. I appreciate your time. I understand that the comma at the end makes the difference.

So the dictionary contains a tuple... where one part of the tuple is None?
(Mar-09-2019, 04:16 PM)inselbuch Wrote: [ -> ]So the dictionary contains a tuple... where one part of the tuple is None?

Yes... no. The dictionary contains a tuple. The tuple contains one thing, which is tuple[0], which is 'hello'. The comma is not in the output to show that there is a second None item, it is there to show that it is a tuple and not just a set of parentheses.