Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python If then Else style when getting values from Dicts

I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything).

Is one of these better and or right/wrong?

value = None
if 'value' in some_dict:
  value = some_dict['value']

some_func(value=value)

OR:

if 'value' in some_dict:
  value = some_dict['value']
else:
  value = None

some_func(value=value)

OR:

some_func(value=some_dict.get('value', None))

I could see reasons for all.

like image 884
ScottZ Avatar asked Jan 04 '12 17:01

ScottZ


1 Answers

Of course the last one is the best - described situation is exact case for dict.get.

Just a note - second parameter to get is superfluous, you can simply write:

some_func(value=some_dict.get('value'))
like image 99
Roman Bodnarchuk Avatar answered Oct 21 '22 08:10

Roman Bodnarchuk