-2

I'm trying to create a dictionary of built in methods but I'm getting the output as shown in below. Why is this happening? I just want to understand that.

>>>
>>> dict = {'a': print('avc'), 'b': print('bbbb'), 'c': print('aaa')}
avc
bbbb
aaa
>>> dict
>>> {'a': None, 'b': None, 'c': None}
>>>

Also, if someone is trying to understand where I'm coming from then they can have a look at this question: Link to the question I was trying to solve when I thought the above would be useful.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Gourav Chawla
  • 470
  • 1
  • 4
  • 12

3 Answers3

3

Because you call the function print while the dictionary is created. You're storing the result of the calls in the dictionary , not the function print. As a result, your dictionary is going to be populated by None values representing the return value of the print calls.

What you should do is have a structure like:

d = {'abc': print} 

And now your dictionary will store the actual function {'abc', <function print>}

You can then call these functions by iterating through the values of the dictionary:

for str, func in d.items():
    func(str)

# prints abc

Additionally, you need to avoid using names like dict for your variables. They mask the built-in types for python (in your case the dict built-in type).

Generally opt for other names, like d.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks for the answer. Now, I understand that I was storing the function calls which caused the NONE value to be stored in corresponding key. I tried other functions which return a value and it stored those value, so my query has been answered. – Gourav Chawla Nov 10 '15 at 14:14
  • Exactly, you've got it perfectly! :-) Just remember next time you try and ask a question on here it is good to include the code *in* the question itself (so you don't get downvoted and all). I have edited your question and added the code for now but just remember that. Good day, Gourav. – Dimitris Fasarakis Hilliard Nov 10 '15 at 14:17
  • 1
    I didn't know that dict was a keyword; I always try to use meaningful names and avoid any name conflicts or masking in this case. – Gourav Chawla Nov 10 '15 at 14:18
  • 1
    Thanks and I'll remember the tip about screenshot. – Gourav Chawla Nov 10 '15 at 14:21
0

print is a function that prints stuff to the screen, and returns None

When you do an assignment, you are saying " the hash value a equals what print("avc") returns"

This means print("avc") is invoked (which is why you see the value printed) and it returns None, so the value of a is None in your dict.

mikeb
  • 10,578
  • 7
  • 62
  • 120
0

Print doesn't return a value.

Imagine it's definition like this

(void) print(object):
   do magic io stuff to make object appear in the console

Therefore, when you are assigning print('avc') for key 'a' in the dictionary, it gets a none.

Zoltan Ersek
  • 755
  • 9
  • 28