python 3.x - Throwing KeyError vs searching key in dictionary using keyword 'in' -
so have search if key nowadays in dictionary or not. post: here
i can see intended way check using:
if key in dict
but questions is, would improve this:
def appendtomydict(key, value): try: old_value = dict[key] newvalue = old_value + value dict[key] = newvalue except keyerror: dict[key] = value
my intention optimize "getting key" much can, because key space large, around 1000 or above.
the way see dictionaries hashmaps. when dict[key], python hashing key, , have been getting value in o(1) time. while searching key using "if key in dict" method, take time o(n)[because searching through whole key space].
but if throw error, take time of o(1) + time throw , grab error.
am right ?
key in dict
o(1), assuming dict
dictionary.
python-3.x
No comments:
Post a Comment