How to use if / else in understanding a dictionary?

In python2.7 +, there is any way to do something like:

{ something_if_true if condition else something_if_false for key, value in dict_.items() } 

I know you can do anything with "if"

 { something_if_true for key, value in dict_.items() if condition} 
+79
python dictionary dictionary-comprehension
Feb 25 2018-12-12T00:
source share
3 answers

You already have: A if test else B is a valid python expression. The only problem with your understanding of dict, as shown, is that the place of an expression in the understanding of dict must have two expressions separated by a colon:

 { (some_key if condition else default_key):(something_if_true if condition else something_if_false) for key, value in dict_.items() } 

The final if clause acts as a filter that differs from the conditional expression.

+147
Feb 25 2018-12-12T00:
source share

@Marcin's answer covers all of this, but in case anyone wants to see a real example, I will add two below:

Let's say you have the following dictionary of sets

 d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}} 

and you want to create a new dictionary whose keys indicate whether the string 'a' contained in the values, you can use

 dout = {"a_in_values_of_{}".format(k) if 'a' in v else "a_not_in_values_of_{}".format(k): v for k, v in d.items()} 

which gives

 {'a_in_values_of_key1': {'a', 'b', 'c'}, 'a_not_in_values_of_key2': {'bar', 'foo'}, 'a_not_in_values_of_key3': {'sad', 'so'}} 

Now suppose you have two such dictionaries

 d1 = {'bad_key1': {'a', 'b', 'c'}, 'bad_key2': {'foo', 'bar'}, 'bad_key3': {'so', 'sad'}} d2 = {'good_key1': {'foo', 'bar', 'xyz'}, 'good_key2': {'a', 'b', 'c'}} 

and you want to replace the keys in d1 with the keys d2 if the corresponding values ​​are identical, you can do

 # here we assume that the values in d2 are unique # Python 2 dout2 = {d2.keys()[d2.values().index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()} # Python 3 dout2 = {list(d2.keys())[list(d2.values()).index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()} 

which gives

 {'bad_key2': {'bar', 'foo'}, 'bad_key3': {'sad', 'so'}, 'good_key2': {'a', 'b', 'c'}} 
+6
Nov 14 '17 at 16:59
source share

Suppose I want to create a grading dictionary that displays grades with grades, for example

  Marks Grade 0-40 - F 40-50 - D 50-60 - C and so on 

For this, I can use a vocabulary understanding with several, if still the conditions shown below:

  marks_dict = {x:"F" if x<40 else "D" if x<50 else "C+" if x<60 else "C" if x<70 else "B+" if x<80 else "A" if x<90 else "A+" if x<=100 else "NULL" for x in range(0,101)} 

This is how you can use several if conditions in understanding the dictionary, but please make sure that there is the last else block at the end, otherwise an error message will be displayed.

Thank you

0
Mar 27 '19 at 13:18
source share



All Articles