Python Forum
curious syntax with dictionary item - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: curious syntax with dictionary item (/thread-16671.html)



curious syntax with dictionary item - inselbuch - Mar-09-2019

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


RE: curious syntax with dictionary item - ichabod801 - Mar-09-2019

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'.


RE: curious syntax with dictionary item - inselbuch - Mar-09-2019

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?


RE: curious syntax with dictionary item - ichabod801 - Mar-09-2019

(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.