Python Forum
curious syntax with dictionary item
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
curious syntax with dictionary item
#1
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
Reply
#2
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'.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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?
Reply
#4
(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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Curious about decorator syntax rjdegraff42 14 1,976 May-03-2023, 01:21 PM
Last Post: rjdegraff42
  python dictionary syntax nafshar 2 840 Apr-24-2023, 07:26 PM
Last Post: snippsat
  Remove an item from a list contained in another item in python CompleteNewb 19 5,550 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  How to modify item in dictionary? Winfried 7 3,387 Nov-21-2020, 07:12 PM
Last Post: bowlofred
  Lists first item is a number however i cant compare it with an int getting syntax err Sutsro 4 2,361 Apr-22-2020, 10:22 AM
Last Post: Sutsro
  A Dictionary in a Dictionary Syntax PythonGainz 3 2,111 Apr-16-2020, 07:16 AM
Last Post: TomToad
  looking fo an expression that yields a dictionary without an item Skaperen 5 2,884 Apr-09-2019, 02:05 AM
Last Post: Skaperen
  deleting item from dictionary Skaperen 6 3,005 Feb-20-2019, 01:18 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020