0

I am trying to learn how to dispatch an action that is related to an element of a dictionary.

I´ve seen a lot of times the formula dictionary[element].function(), and there the function calls the element of the dictionary.

I am trying to do that with this code, but I can not get the working method.

Any ideas?

(The last line of the code is the syntax that I want to use)

Thank you in advance!

def function(arg):
    print 'Running ' + str(arg)

data={}
data[0]={'name':'Ruben', 'run':function}
data[1]={'name':'David', 'run':function}

print data
data[0].run()
bastelflp
  • 9,362
  • 7
  • 32
  • 67
Ruben Medrano
  • 161
  • 2
  • 10
  • Did you mean `data[0]['run']()`? You can't access values using the key like an attribute in vanilla Python dictionaries, and a dictionary doesn't have a callable attribute named `run`. – jonrsharpe Feb 11 '16 at 21:30
  • Hello jonsharpe, yes, I mean that. But I´ve seen that a lot of times (in the format of the last line of the code) and I will like to learn how to do it. – Ruben Medrano Feb 11 '16 at 21:36
  • Then you need to put the correct thing into the `data` dictionary, i.e. some object with a callable `run` attribute. – jonrsharpe Feb 11 '16 at 21:37
  • 1
    @RubenMedrano That isn't what a dictionary is for. It may be [classes](https://docs.python.org/2/tutorial/classes.html) that you are interested in. – zondo Feb 11 '16 at 21:39
  • Are you sure you aren't mixing up Python and some other language? Javascript, perhaps? – user2357112 Feb 11 '16 at 21:43

1 Answers1

2

Use data[0]['run']('Hello World!'). This executes the function with the argument Hello World! and prints:

Running Hello World!
bastelflp
  • 9,362
  • 7
  • 32
  • 67