Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python safe dictionary key access [duplicate]

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 ifs or custom functions?

I believe there should be, because this is a very common usage.

like image 508
nipunasudha Avatar asked Dec 15 '17 12:12

nipunasudha


People also ask

Is duplicate key allowed in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Is duplicate keys are allowed in dictionary?

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<> .

Are Python dict threads safe?

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.


1 Answers

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') 
like image 162
Martijn Pieters Avatar answered Sep 29 '22 07:09

Martijn Pieters