How can I use if/else in a dictionary comprehension?

后端 未结 4 1739
长发绾君心
长发绾君心 2020-11-28 20:40

Does there exist a way in Python 2.7+ to make something like the following?

{ something_if_true if condition else something_if_false for key, value in d         


        
4条回答
  •  感情败类
    2020-11-28 20:58

    @Marcin's answer covers it all, but just in case someone wants to see an actual example, I 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' is contained in the values or not, 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 yields

    {'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 let's suppose you have two dictionaries like this

    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 by the keys of d2 if there respective values are identical, you could 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'}}
    

提交回复
热议问题