Check for a value in a set and variable assignment

Given this set and the GET input parameter that indicates the selected fruit

fruit = {'apple', 'banana', 'orange', 'pear'} 

Is there a compact way to do this on a single line in python?

 chosen = request_obj.get('fruit', '') if chosen not in fruit: chosen = '' 
+4
source share
3 answers

Here's another way:

 >>> fruit = {'apple','banana','orange','pear'} >>> d = {'fruit': 'apple'} >>> d['fruit'] if 'fruit' in d and d['fruit'] in fruit else '' 'apple' >>> d['fruit'] = 'watermellon' >>> d['fruit'] if 'fruit' in d and d['fruit'] in fruit else '' '' 

Honestly, I think you have a more readable and better choice.

+1
source

You can just do -

 fruit = {'apple', 'banana', 'orange', 'pear'} input_get_param = 'some_other_fruit' if input_get_param in fruit: chosen = input_get_param print 'pear is in the set' else: chosen = '' 

I prefer to search for a set first, since the python set implementation uses a hash table as the underlying data structure. This explains the O (1) membership check, since finding an item in a hash table is an O (1) operation on average. Therefore, the search is pretty cheap.

0
source
 >>> fruit = {'apple','banana','orange','pear'} >>> d = {'fruit': 'apple'} >>> chosen = '' if d.get('fruit','') not in fruit else d.get('fruit','') >>> chosen 'apple' >>> d['fruit'] = 'watermellon' >>> chosen = '' if d.get('fruit','') not in fruit else d.get('fruit','') >>> chosen '' 
0
source

All Articles