python - Are quoted dictionary keys an absolute must? -
python - Are quoted dictionary keys an absolute must? -
just curious, made interesting observation got away defining dictionary keys without having quote them. guess vulnerability in python?
within sample, , not in repl, next not raise exception:
>>> {foo:'foo', bar:'bar'} traceback (most recent phone call last): file "<stdin>", line 1, in <module> nameerror: name 'foo' not defined how pythonistas handle keys? advocate unquoted or quoted keys, , why?
a dictionary's keys can hashable object (a string, integer, tuple, etc.):
>>> dct = {'a': 1, 1: 'a'} >>> dct['a'] 1 >>> dct[1] 'a' >>> quoting key means key string, 'a' above.
as far claim that:
i got away defining keys without having quote them
i assume mean did this:
dct = {key1: 1, key2: 'a'} there nil special code above. means names key1 , key2 refer hashable objects, become keys of dictionary. illustration below:
>>> key1 = 'a' >>> key2 = 1 >>> dct = {key1: 1, key2: 'a'} >>> dct[key1] 1 >>> dct[key2] 'a' >>> dct['a'] 1 >>> dct[1] 'a' >>> on other hand, if mean used dict built-in create dictionary:
dct = dict(key1='a', key2=1) then should know keys still normal strings:
>>> dct = dict(key1='a', key2=1) >>> dct {'key2': 1, 'key1': 'a'} >>> dct[key1] traceback (most recent phone call last): file "<stdin>", line 1, in <module> nameerror: name 'key1' not defined >>> dct['key1'] 'a' >>> finally, regarding question of whether or not should utilize string keys, reply it depends. if need keys hold info can represented string (such person's name), utilize strings. if need keys hold numerical info (such id numbers), utilize integers or floats or whatever appropriate.
simply put, whatever makes sense program.
python dictionary key
Comments
Post a Comment