[英]python: getting the key value within the value of dictionary
i want to pass the key string into the lambda function as argument for mn
within the same line. 我想将密钥字符串作为同一行中
mn
参数传递给lambda函数。 Is there a way to do that? 有没有办法做到这一点? i don't want to retype the key string again.
我不想再次输入密钥字符串。
switch = {
'foo': lambda: bb.Data(ticker=self.ticker, key=self.key, func='yes', mn='foo'),
'bar': lambda: bb.Data(ticker=self.ticker, key=self.key, mn='bar')
}
You can create the dictionary like this: 您可以这样创建字典:
switch = {
key: lambda: do_something(key)
for key in ['foo', 'bar']
}
If you want to call a different function for a different key, you would need something like this: 如果要为不同的键调用不同的函数,则需要这样的操作:
def add_dict_item(a_dict, key):
if key == 'foo':
a_dict[key] = lambda: do_something(key)
elif key == 'bar':
a_dict[key] = lambda: do_something_else(key)
switch = {}
add_dict_item(switch, 'foo')
add_dict_item(switch, 'bar')
You can define a member function since you have used self. 由于您使用过self,因此可以定义成员函数。 And use dictionary comprehension.
并使用字典理解。
def mn_func(self, mn_item):
return bb.Data(ticker=self.ticker, key=self.key, mn=mn_item)
list_of_items = ['foo', 'bar']
switch ={ mn_item:mn_func(mn_item) for mn_item in list_of_items}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.