我有一个dict,其中我加载了一些信息,其中一个名称是一个普通的字符串.但不知何故,当我将它分配给dict中的一个键时,它会转换为一个元组,我不知道为什么.
这是我的一些代码:
sentTo = str(sentTo)
print type(sentTo), sentTo
ticketJson['sentTo'] = sentTo,
print type(ticketJson['sentTo']), ticketJson['sentTo']
在我的终端输出以下内容:
<type 'str'> Pete Chasin
<type 'tuple'> ('Pete Chasin',)
为什么将它分配给dict会将其转换为元组?
解决方法:
你告诉Python创建一个包含字符串的元组:
ticketJson['sentTo'] = sentTo,
# ^
它是定义元组的逗号.只需要括号来消除元组与逗号的其他用法的歧义,例如在函数调用中.
Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
从Expression lists开始:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.