I have the following dictionary:
dic = {"a": "first", "b": "second"}
and it’s ok, when I do the following:
print dic.get("a")
print dic.get("a", "asd")
print dic.get("a", dic.get("c"))
but when I use this method like this:
print dic.get("a", dic.get("c").split(" ",1)[0])
I receive the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'split'
I dont’t understand the last case. The second argument calculated (dic.get(“c”) should be None – it’s ok), but there is a key “a” in dictionary and first argument shouldn’t fire calculating of the second argument.
How I can fix this? And why it happened?
TIA!
As others have explained, Python (like most other languages outside the functional family) evaluates all arguments of a function before calling it. Thus,
dic.get("c")isNonewhen key “c” doesn’t exist in the dictionary andNonehas no.split()method, and this evaluation happens regardless of whether (and in fact before) thegetsucceeds or fails.Instead, use a short-circuiting Boolean operator or a conditional expression.