Can someone explain the output of the attached python dictionary test? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone explain the output of the attached python dictionary test?

I believe it's indexing the dictionary but it returns false. I would have expected it to return true. https://code.sololearn.com/cAN3212p8Ql2/?ref=app

24th Mar 2019, 4:46 PM
Jrp
5 Answers
+ 4
Dictionaries are meant to work like this: You say a word (key) and they give you what's stored under that word. d = {'word': 'whatever'} print(d['word']) output: whatever Keep this in mind. Now if you want to see if a dictionary entry is true or false, you are asking for the value that is stored: is it true or is it false? False are for example 0, '' and every empty iterable, true is any number except 0, any string that has actual letters and any iterable with at least one item in it. d = {1: 0, 2: 'hey', 3: None, 4: [], 5: True} Now if you check all of these for their bool, you'll get False, True, False, False, True. Because that's how the values evaluate.
24th Mar 2019, 5:30 PM
HonFu
HonFu - avatar
+ 5
Jrp The second half does not make sense. If you want it to be true then you must change it as follow. d={None:None} if d[None]==None: print("true") else: print("false")
24th Mar 2019, 5:32 PM
Louis
Louis - avatar
+ 3
Jrp d[None] is None and bool(None) is False, so the output is 'false'
24th Mar 2019, 4:52 PM
portpass
+ 1
HonFu Thx for that explanation. I definitely was reading it wrong. It's not testing if the key equals that value, rather testing if the value is true. Thx! Louis ignore that 2nd half. That was other testing and wasn't supposed to have been saved. :) Appreciate all the quick responses! Love this app!
24th Mar 2019, 8:09 PM
Jrp
0
Thx for the reply. I still don't quite understand. I feel like because d[None] is None, it is true and should return true. What am I missing?
24th Mar 2019, 5:13 PM
Jrp