2

When I execute the code, it print" function aa in 0x0000... "and all.

I want it to print aa,a,b,c,d,. Is it possible?

Sorry for the stupid question, thanks a lot.

def main():
    lunch = {
        0: aa,
        1: a,
        2: b,
        3: c,
        4: d,
        }

    for i in range(len(lunch)):
        print(lunch[i])
def aa():
    print("aa")
def a():
    pass
def b():
    pass
def c():
    pass
def d():
    pass
if __name__ == "__main__":
    main()        
Frank Wen
  • 39
  • 1
  • 1
  • 3
  • The name of a function is usually stored in it's `__name__` attribute. Lambdas are a notable exception. – Mad Physicist Feb 27 '18 at 08:27
  • Did you mean to have `lunch = { 0: aa, ... }` or did you mean `lunch = { 0: "aa", ... }` ? The later makes the for-loop print what you want , and the following functions aren't usefull anymore. – jadsq Feb 27 '18 at 08:31

4 Answers4

3

If you want to print the name of functions just use __name__ property.

print(lunch[i].__name__)

In case you want to invoke it as a function use paranthesis.

print(lunch[i]())
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
3

here is a simple code that demonstrates what you want:

take this example:

myDic = {"i" : "me" , "you": "you" , "they" : "them"}
for i in myDic:
    print (i)          # this will print all keys
    print (myDic[i])   # this will print all values

NOTE: you also need to surround your values with quotes like this "aa"

amdev
  • 6,703
  • 6
  • 42
  • 64
1

Change this part to:

for i in range(len(lunch)):
    print(lunch[i].__name__)

At the moment you are printing the function instead of its name.

jsmolka
  • 780
  • 6
  • 15
1
def main():
    lunch = {
        0: 'aa',
        1: 'a',
        2: 'b',
        3: 'c',
        4: 'd',
        }

    for k, v in lunch.items():
        print(v)

if __name__ == "__main__":
    main() 

I have modified your code as you want to print only values try this.

Hope this helps you! :)

Abdullah Ahmed Ghaznavi
  • 1,978
  • 3
  • 17
  • 27