dict.get()

Every programmer loves a dictionary. The python dict is a hashmap and the average time complexity is o(1). This article explains why you should ditch the usual dict["key"] for dict.get() to obtain dictionary values.

users = {"amalshaji": "Amal Shaji", "gates": "Bill Gates"}

def greet_user(name: str):
    print(f"Hello {users[name]}")
>>> from test import greet_user as g
>>> g("amalshaji")
Hello Amal Shaji
>>> g("hashnode")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/amalshaji/Workspace/python/test.py", line 5, in greet_user
    print(f"Hello {users[name]}")
KeyError: 'hashnode'

This KeyError could exit the program. One way to fix this is to use try. Thus our greet_user becomes,

def greet_user(name: str):
    try:
        print(f"Hello {users[name]}")
    except KeyError as e:
        print(f"Hello {e}")
>>> from test import greet_user as g
>>> g("amalshaji")
Hello Amal Shaji
>>> g("hashnode")
Hello 'hashnode'

dict.get()

Another way is to use dict.get(). We can provide a default value if the key isn't found.

# syntax
dict.get(key, default)
users = {"amalshaji": "Amal Shaji", "gates": "Bill Gates"}

def greet_user(name: str):
    print(f"Hello {users.get(name, 'Unknown')}")
>>> from test import greet_user as g
>>> g("amalshaji")
Hello Amal Shaji
>>> g("hashnode")
Hello Unknown

Happy Hacking✨✨

No Comments Yet