Skip to main content
 首页 » 编程设计

python之我可以传递字典值/条目和键来运行吗

2025年05月04日10jyk

我正在编写一个函数,打算使用字典键及其值作为参数。例如:

testDict={'x':2,'xS':4} 
 
def newFunct(key,testDict['key']): 
    newvalue=key+str(testDict['key']) 
    return newValue 
 
for key in testDict: 
    newValue=newFunct(key,testDict[key]) 
    print newValue 

当我在输入分号后点击返回按钮时,我得到一个 SyntaxError: invalid syntax。我猜这是在告诉我我不能以那种形式传递字典值。大概我可以定义一个新变量

for key in testDict: 
    xdixt=testDict[key] 
    newValue=newFunct(key,xdixt) 

并使用 xdixt 定义函数

但我希望我遗漏了一些技巧。我用 Google 搜索并找到了一些关于解包字典的引用资料,但这似乎没有用。

这个 Python 东西真的很酷。我的问题是因为我试图使用我存储在字典中的一些值来创建一个新目录。根据我从 Stephan 的回答中读到的 Material ,我想知道如何概括我学到的信息。我的目录名有五个不同的部分,每个部分都是处理来自 myDict 的值的结果。创建目录名称的表达式变得太复杂了,在我看来太复杂了,不容易阅读。所以我想知道我是否可以使用相同的方法将这些片段放入列表中,然后在需要创建目录名称时解压缩它们并且它起作用了!

def createDirectory(myKey,**myDict):  
   pathList=[] 
   pathList.append(myDict['subKey1']) 
   pathList.append(myDict['subKey2'].lstrip('0')) 
   pathList.append(myDict['subKey3']) 
   etc   
   myPath=os.path.join(*myList) 
   os.makedirs(myPath) 
   return(myPath) 

请您参考如下方法:

这是你想要的吗?

def func(**kwargs): 
    for key, value in kwargs.items(): 
        pass # Do something 
 
func(**myDict) # Call func with the given dict as key/value parameters 

(有关关键字参数的更多信息,请参阅 documentation。myDict 中的键必须是字符串。)


编辑:您编辑了您的问题以包括以下内容:

I think the ** notation in front of myDict instructs the function to expect a dictionary and to unpack the key (the first *) and the value, the second *

这是不正确的。要了解正在发生的事情,您必须考虑以下几点:

  • 一个函数可以有多个形式参数(在本例中为a 和b):
def f1(a, b): pass
  • We can pass positional arguments to such function (like in most other languages):
f1(2, 3)
  • We can also pass keyword arguments:
f1(a=2, b=3)
  • We can also mix these, but the positional arguments must come first:
f1(2, b=3) 
f1(a=2, 3)  # SyntaxError: non-keyword arg after keyword arg
  • There is a way to let a function accept an arbitrary number of positional arguments, which it can access as a tuple (args in this case):
def f2(*args): assert isinstance(args, tuple)
  • Now we can call f2 using separately specified arguments, or using a list whose contents first need to be unpacked, using a syntax similar to the notation used for *args:
f2(2, 3) 
f2(*[2, 3])
  • Likewise, an arbitrary number of keyword arguments may be accepted:
def f3(**kwargs): pass
  • Note that f3 does not ask for a single argument of type dict. This is the kind of invocations it expects:
f3(a=2, b=3) 
f3(**{'a': 2, 'b': 3})
  • All arguments to f3 must be named:
f3(2, 3)  # TypeError: f3() takes exactly 0 arguments (2 given)

Putting all of this together, and remembering that positional arguments must come first, we may have:

>>> def f4(a, b, *args, **kwargs): 
...     print('%r, %r' % (args, kwargs)) 
...  
>>> f4(2, 3) 
(), {} 
>>> f4(2, 3, 4, 5) 
(4, 5), {} 
>>> f4(2, 3, x=4, y=5) 
(), {'y': 5, 'x': 4} 
>>> f4(2, 3, 4, 5, x=6, y=7) 
(4, 5), {'y': 7, 'x': 6} 
>>> f4(2, *[3, 4, 5], **{'x': 6, 'y': 7}) 
(4, 5), {'y': 7, 'x': 6} 

特别注意以下两个错误:

>>> f4(2) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: f4() takes at least 2 arguments (1 given) 
>>> f4(2, 3, a=4) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: f4() got multiple values for keyword argument 'a' 

第二个错误应该可以帮助您解释此行为:

>>> f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4}) 
(), {'c': 4, 'foo': 0}