jason
jason

Reputation: 4429

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. 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')
}

Upvotes: 0

Views: 90

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

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')

Upvotes: 1

kvivek
kvivek

Reputation: 3461

You can define a member function since you have used 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}

Upvotes: 1

Related Questions