[英]keyword error generated when Passing a dictionary to a function with tuples as the keys
我是 Python 的新手,我正在努力完成傳遞字典的任務,字典的鍵是元組,作為 function 的參數。
mydict = {('hostabc', 'pola'): 333444567, ('hostdef', 'polb'): 111222333, ('hostghi', 'polc'): 222999888}
def tupletest(**kwargs):
print(kwargs)
tupletest(**mydict)
生成以下關鍵字錯誤:
TypeError Traceback (most recent call last)
<ipython-input-29-fec409a1eb53> in <module>
2 def tupletest(**kwargs):
3 print(kwargs)
----> 4 tupletest(**mydict)
TypeError: tupletest() keywords must be strings
鑒於錯誤消息,我不確定這是否可能。 我在3.7.4中對此進行測試
所有幫助表示贊賞。
我做了一個小例子。 有可能:
mydict = {('hostabc', 'pola'): 333444567, ('hostdef', 'polb'): 111222333, ('hostghi', 'polc'): 222999888}
def tupletest(kwargs):
for key in kwargs:
#print("key: %s , value: %s" % (key, kwargs[key]))
print(key[0])
print(key[1])
tupletest(mydict)
我希望這可以幫助你。 我還實現了一個輸入字典鍵的小例子。
簡短的回答是,不,這是不可能的。
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
**kwargs
代表關鍵字 arguments。 這些 arguments 被解包(可以這么說)並傳遞給 function。 這樣,您可以在 function 中使用它們,而無需將它們作為位置或關鍵字 arguments 顯式傳遞給 function。
def func(*args, **kwargs): ...
var-keyword:指定可以提供任意多個關鍵字arguments(除了已經被其他參數接受的任何關鍵字arguments)。 可以通過在參數名稱前加上 ** 來定義這樣的參數,例如上面示例中的 kwargs。
@BoarGules 很好地為您指明了路徑。 我沒有什么新東西要補充的,我在下面說的是同一件事,但有點冗長。
在這里看到這個很好的討論。 因此字典鍵成為 function 的命名參數。 然而,在這種特殊情況下,鍵是元組。 關鍵字必須具有關聯的字符串屬性,這就是上面的錯誤所說的。 請注意下面錯誤消息中的“字符串”。
TypeError: tupletest() keywords must be strings
如果你的字典像下面這樣更簡單,它會起作用的。
mydict = {"a": 333444567, "b": 111222333, "c": 222999888}
def tupletest(**kwargs):
for k in kwargs:
print(k)
tupletest(**mydict)
上面給出了這個。
a
b
c
如果你想擁有元組,我會在引用元組后采取危險的 eval 路線。
mydict = {"('hostabc', 'pola')": 333444567, "('hostdef', 'polb')": 111222333, "('hostghi', 'polc')": 222999888}
def tupletest(**kwargs):
for k in kwargs:
print(eval(k))
tupletest(**mydict)
這給出了以下 output。
('hostabc', 'pola')
('hostdef', 'polb')
('hostghi', 'polc')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.