Reputation: 445
I started learning about dictionaries in Python.
For the following dictionary:
nameMap={1: "Bob", 2: "Pete", 3: "Ben", 4: "Bud", 5: "Russ"}
In order to obtain a value, the outputs are slightly different when using print(nameMap[1])
and nameMap[1]
.
Can you explain what is exactly going here?
Upvotes: 0
Views: 815
Reputation: 1866
print(nameMap[1])
just prints the value out on console (or whatever output system you're using).
nameMap[1]
just returns the value contained by the dict, whatever the type is. In order to know what type the value is, type(nameMap[1])
.
Upvotes: 1
Reputation: 1043
This is what is means:
nameMap[1]
will return a str
type object
print(nameMap[1])
will return a NoneType
object
Here is the supporting code:
When in confusion, use the type()
method to check the type of a value.
>>> nameMap = {1: "Bob", 2: "Pete", 3: "Ben", 4: "Bud", 5: "Russ"}
>>> nameMap[1]
'Bob'
>>> type(nameMap[1])
<class 'str'>
>>> print(nameMap[1])
Bob
>>> type(print(nameMap[1]))
Bob
<class 'NoneType'>
Upvotes: 2
Reputation: 10430
in order to obtain a value, the out puts are slightly different when using print(nameMap[1]) and nameMap[1]. Can you explain what is exactly going here. Thank you.
I think you mean the difference between "when you try to print the value of a variable using explicit print
call" vs "without using print
by typing the variable name directly over the interpreter".
I have tired your code with my interpreter:
Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> nameMap={1: "Bob", 2: "Pete", 3: "Ben", 4: "Bud", 5: "Russ"}
>>> print(nameMap[1])
Bob
>>> nameMap[1]
'Bob'
>>>
My guess is that the difference in printing is due to the difference in the __repr__
and __str__
method of the class.
print(variable)
equals to print(str(variable))
whereas
variable equals to print(repr(variable))
.
Try this too:
>>> print(nameMap[1])
Bob
>>> nameMap[1]
'Bob'
>>> print(repr(nameMap[1]))
'Bob'
>>>
Upvotes: 1