find the value associated with a key in a map in python

In Python, the map data structure is called a dictionary. To find the value associated with a key in a Python dictionary, you can simply use the key as an index:

main.py
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
print(my_dict["key2"])  # prints "value2"
107 chars
3 lines

If the key is not present in the dictionary, this will raise a KeyError. To avoid this, you can use the .get() method, which returns None if the key is not present:

main.py
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
print(my_dict.get("key4"))  # prints "None"
109 chars
3 lines

You can also provide a default value to the .get() method, so that it returns the default value instead of None:

main.py
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
print(my_dict.get("key4", "default_value"))  # prints "default_value"
135 chars
3 lines

related categories

gistlibby LogSnag