将字典传递给以元组作为键的函数时生成的关键字错误

keyword error generated when Passing a dictionary to a function with tuples as the keys

我是 Python 的新手,我正在努力完成将键为元组的字典作为函数参数传递的任务。

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)

希望对您有所帮助。我还实现了一个输入字典键的小例子。

Output

简短的回答是,不,这是不可能的。

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

**kwargs 表示关键字参数。这些参数是 unpacked (这么说) 并传递给函数。这样您就可以在函数中使用它们,而不必将它们作为位置或关键字参数显式传递给函数。

def func(*args, **kwargs): ...

var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with **, for example kwargs in the example above.

https://docs.python.org/3/glossary.html#term-argument

@BoarGules 很好地为您指出了路径。我没有什么新的要补充的,我在下面说同样的话,但有点冗长。

看到这个不错的讨论 here。所以字典键成为函数的命名参数。然而,在这种特殊情况下,键是元组。关键字必须有一个关联的字符串 属性 ,这就是上面的错误所说的。请注意下面错误消息中的“strings”。

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)

这给出了以下输出。

('hostabc', 'pola')
('hostdef', 'polb')
('hostghi', 'polc')