我可以通过字典值/输入和键进行功能 [英] Can I Pass Dictionary Values/Entry and Keys to function

查看:121
本文介绍了我可以通过字典值/输入和键进行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  testDict = {'x':2,'xS':4} 

def newFunct(key,testDict ['key']):
newvalue = key + str(testDict ['key'])
返回newValue

为testDict中的键:
newValue = newFunct(key,testDict [key])
打印newValue

当输入分号后,我点击返回按钮,得到一个SyntaxError:无效的语法。我猜这是告诉我,我不能通过这种形式的字典值。大概我可以为testDict中的键定义一个新变量

 
xdixt = testDict [key]
newValue = newFunct(key,xdixt)

并使用xdixt定义函数



但我希望有一些我错过的技巧。我已经Google Googled,并找到一些引用拆包字典,但似乎不起作用。



这个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)


解决方案

不知道为什么我们带来kwargs,这比这简单得多。你说你是Python的新手,我想你只需要一些Python的基础知识。

  def newFunct(key,testDict [ 'key']):

应该是:

  def newFunct(key,val):

没有理由在您的第二个参数上使用任何特殊语法来表示它来自字典。这只是一个参数,你只是碰巧将一个字典项目的值传递给它。



此外,一旦它在功能中,没有理由对待也是一种特殊的方式。在这一点上,这只是一个价值。这意味着:

  newvalue = key + str(testDict [key])

现在可以:

  newvalue = key + str(val)

所以当你像这样调用它: >

  newValue = newFunct(key,testDict [key])

testDict [key]解析为key的值,该值在函数中变为val。






另一种方式是,如果你看到它适合任何原因(这只是一件很好的知道),你可以定义这个功能:

  def newFunct(key,testDict):

再次,第二个参数只是一个参数,所以我们使用相同的语法,但现在我们期望它是一个dict,所以我们应该像一个使用它:

  newvalue = key + str(testDict [key])

(注意:不要把引号放在'键'在这种情况下,我们指的是名为'key'的变量,而不是一个叫'key'的键。当你调用函数时,它看起来像这样:

  newValue = newFunct(key,testDict)

与第一种情况不同的是,您只需从字典中传递一个变量,就可以将整个字典的引用传递给这一次的功能。



希望有所帮助。


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

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

and def the function using 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!

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)

解决方案

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.

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.


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:

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:

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.

这篇关于我可以通过字典值/输入和键进行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆