python 我可以通过字典值/条目和键来运行吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/853483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I Pass Dictionary Values/Entry and Keys to function
提问by PyNEwbie
I am writing a function and intended to use a dictionary key and its value as parameters. For example:
我正在编写一个函数并打算使用字典键及其值作为参数。例如:
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
I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable
我在输入分号后点击返回按钮时收到 SyntaxError: invalid syntax 。我猜这告诉我我不能以这种形式传递字典值。大概我可以定义一个新变量
for key in testDict:
xdixt=testDict[key]
newValue=newFunct(key,xdixt)
and def the function using xdixt
并使用 xdixt 定义函数
but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work.
但我希望有一些我遗漏的技巧。我在谷歌上搜索并找到了一些解压缩字典的参考,但这似乎不起作用。
This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked!
这个 Python 的东西真的很酷。我的问题是因为我试图使用我存储在字典中的一些值来创建一个新目录。根据我从 Stephan 的回答中读到的材料,我想知道如何概括我学到的信息。我的目录名称有五个不同的部分,每个部分都是处理来自 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)
回答by Stephan202
Is this what you want?
这是你想要的吗?
def func(**kwargs):
for key, value in kwargs.items():
pass # Do something
func(**myDict) # Call func with the given dict as key/value parameters
(See the documentationfor more about keyword arguments. The keys in myDict
must be strings.)
(有关关键字参数的更多信息,请参阅文档。输入的键myDict
必须是字符串。)
Edit: you edited your question to include the following:
编辑:您编辑了您的问题以包括以下内容:
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 *
我认为 myDict 前面的 ** 符号指示函数期望字典并解压缩键(第一个 *)和值,第二个 *
This is not correct. To understand what is happening, you must consider the following:
这是不正确的。要了解正在发生的事情,您必须考虑以下几点:
- A function can have multiple formal parameters(
a
andb
in this case):
- 一个函数可以有多个形式参数(
a
和b
在这种情况下):
def f1(a, b): pass
- We can pass positional argumentsto 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):
- 有一种方法可以让函数接受任意数量的位置参数,它可以作为元组访问(
args
在这种情况下):
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
使用单独指定的参数调用,或者使用一个列表,其内容首先需要被解包,使用类似于用于的符号的语法*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 notask for a single argument of typedict
. This is the kind of invocations it expects:
- 请注意,
f3
它不要求类型为单个参数dict
。这是它期望的调用类型:
f3(a=2, b=3) f3(**{'a': 2, 'b': 3})
- All arguments to
f3
must be named:
- 所有参数都
f3
必须命名为:
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}
Pay special attention to the following two errors:
特别注意以下两个错误:
>>> 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'
The second error should help you explain this behavior:
第二个错误应该可以帮助您解释这种行为:
>>> f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4})
(), {'c': 4, 'foo': 0}
回答by Stephan202
Not sure why we are bringing in kwargs, this is much simpler than that. You said you're new to Python, I think you just need some Python fundamentals here.
不知道为什么我们要引入 kwargs,这比那简单得多。你说你是 Python 的新手,我认为你在这里只需要一些 Python 基础知识。
def newFunct(key,testDict['key']):
Should be:
应该:
def newFunct(key, val):
There's no reason to use any special syntax on your second parameter to indicate that it's coming from a dictionary. It's just a parameter, you just happen to be passing the value from a dictionary item into it.
没有理由在第二个参数上使用任何特殊语法来表明它来自字典。它只是一个参数,您只是碰巧将字典项中的值传递给它。
Further, once it's in the function, there's no reason to treat it in a special way either. At this point it's just a value. Which means that:
此外,一旦它在函数中,也没有理由以特殊方式对待它。在这一点上,它只是一个值。意思就是:
newvalue=key+str(testDict[key])
Can now just be:
现在可以只是:
newvalue=key+str(val)
So when you call it like this (as you did):
所以当你这样称呼它时(就像你所做的那样):
newValue=newFunct(key,testDict[key])
testDict[key] resolves to the value at 'key', which just becomes "val" in the function.
testDict[key] 解析为 'key' 处的值,它在函数中变成了“val”。
An alternate way, if you see it fit for whatever reason (and this is just something that's good to know), you could define the function thusly:
另一种方式,如果您认为它适合任何原因(这只是一个很好的了解),您可以这样定义函数:
def newFunct(key, testDict):
Again, the second parameter is just a parameter, so we use the same syntax, but now we're expecting it to be a dict, so we should use it like one:
同样,第二个参数只是一个参数,所以我们使用相同的语法,但现在我们期望它是一个 dict,所以我们应该像这样使用它:
newvalue=key+str(testDict[key])
(Note: don't put quotes around 'key' in this case. We're referring to the variable called 'key', not a key called 'key'). When you call the function, it looks like this:
(注意:在这种情况下,不要在 'key' 周围加上引号。我们指的是名为 'key' 的变量,而不是名为 'key' 的键)。当您调用该函数时,它看起来像这样:
newValue=newFunct(key,testDict)
So unlike the first case where you're just passing one variable from the dictionary, you're passing a reference to the whole dictionary into the function this time.
因此,与您只从字典中传递一个变量的第一种情况不同,这次您将整个字典的引用传递给函数。
Hope that helps.
希望有帮助。
回答by SilentGhost
why don't you just do:
你为什么不这样做:
[k + str(v) for k, v in test_dict.iteritems()]
or for py3k:
或对于 py3k:
[k + str(v) for k, v in test_dict.items()]
edit
编辑
def f(k, v):
print(k, v) # or do something much more complicated
for k, v in testDict.items():
f(k, v)
回答by Roee Adler
From your description is seems like testDict is some sort of global variable with respect to the function. If this is the case - why do you even need to pass it to the function?
从你的描述来看, testDict 似乎是某种关于函数的全局变量。如果是这种情况 - 为什么你甚至需要将它传递给函数?
Instead of your code:
而不是你的代码:
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
You can simply use:
您可以简单地使用:
testDict={'x':2,'xS':4}
def newFunct(key):
newvalue=key+str(testDict[key])
return newValue
for key in testDict:
newValue=newFunct(key)
print newValue
If testDict is not meant to be in the global scope (which makes sense...), I would recommend simply passing a name for the dictionary and not "messing around" with variable length argument lists in this case:
如果 testDict 不打算在全局范围内(这是有道理的......),我会建议简单地传递字典的名称,而不是在这种情况下“乱七八糟”可变长度参数列表:
testDict={'x':2,'xS':4}
def newFunct(key,dictionary):
newvalue=key+str(dictionary[key])
return newValue
for key in testDict:
newValue=newFunct(key,testDict)
print newValue