簡體   English   中英

使用字符串更新Python字典以設置(鍵,值)失敗

[英]Update Python Dictionary with Tuple of Strings to set (key, value) fails

dict.update([other])

更新與來自其他 ,覆蓋現有密鑰的密鑰/值對的字典。 返回

update()接受另一個字典對象或一對鍵/值對的迭代(作為元組或長度為2的其他迭代)。 如果指定了關鍵字參數,則使用這些鍵/值對更新字典:d.update(red = 1,blue = 2)。

>>> {}.update( ("key", "value") )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required

那么為什么Python顯然會嘗試使用元組的第一個字符串?

立即溶液是這樣的:唯一的參數other任選的 ,元組(或長度的兩個其他iterables)的迭代

沒有爭論(它是可選的,因為當你不需要它時:-):

>>> d = {}
>>> d.update()
>>> d
{}

帶有元組的列表(不要將它與包含可選參數的方括號混淆!):

>>> d = {}
>>> d.update([("key", "value")])
>>> d
{'key': 'value'}

根據迭代Python術語表 ,元組(作為所有序列類型)也是可迭代的,但是這會失敗:

>>> d = {}
>>> d.update((("key", "value")))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required

關於tuplePython文檔再次解決了這個謎團:

請注意,它實際上是一個逗號,它產生一個元組,而不是括號。 括號是可選的,除了空元組情況,或者需要它們以避免語法歧義。

(None)根本不是元組,但是(None,)是:

>>> type( (None,) )
<class 'tuple'>

這樣可行:

>>> d = {}
>>> d.update((("key", "value"),))
>>> d
{'key': 'value'}
>>>

但事實並非如此

>>> d = {}
>>> d.update(("key", "value"),)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required

因為所說的句法歧義 (逗號是函數參數分隔符)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM