python - .get and dictionaries -


i'm new python programmer , reading on .get method dictionaries, tried use myself. tried simple code:

h = dict() h.get('a', 1) print (h) 

and interpreter returned only:

{} 

i know .get method returns default value provide if can't find key asked for, go , create new key , bucket in dictionary? if so, why doesn't code return new item? thanks

no, get not add entry dict if 1 doesn't exist. makes no modifications.

>>> h = dict() >>> h.get('a', 1) 1 >>> h {} 

the same goes [] when reading dict; throw error non-existent keys. different c++, [] add entries if aren't there already.

>>> h['a'] traceback (most recent call last):   file "<stdin>", line 1, in <module> keyerror: 'a' >>> h {} 

but know python can differentiate between reads , writes. assigning non-existent key create it, though reading non-existent key raises exception.

>>> h['a'] = 1 >>> h {'a': 1} 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -