I am looking for a convenient, safe python dictionary key access approach. Here are 3 ways came to my mind.
data = {'color': 'yellow'} # approach one color_1 = None if 'color' in data: color_1 = data['color'] # approach two color_2 = data['color'] if 'color' in data else None # approach three def safe(obj, key): if key in obj: return obj[key] else: return None color_3 = safe(data, 'color') #output print("{},{},{}".format(color_1, color_2, color_3))
All three methods work, of-course. But is there any simple out of the box way to achieve this without having to use excess if
s or custom functions?
I believe there should be, because this is a very common usage.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
Many common operations on a dict are atomic, meaning that they are thread-safe. Atomic means that the operation either occurs or does not occur with no in between inconsistent state. Operations such as adding, removing, and reading a value on a dict are atomic.
You missed the canonical method, dict.get()
:
color_1 = data.get('color')
It'll return None
if the key is missing. You can set a different default as a second argument:
color_2 = data.get('color', 'red')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With