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

后端 未结 4 1721
长发绾君心
长发绾君心 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:48

    In case you have different conditions to evaluate for keys and values, @Marcin's answer is the way to go.

    If you have the same condition for keys and values, you're better off with building (key, value)-tuples in a generator-expression feeding into dict():

    dict((modify_k(k), modify_v(v)) if condition else (k, v) for k, v in dct.items())
    

    It's easier to read and the condition is only evaluated once per key, value.

    Example with borrowing @Cleb's dictionary of sets:

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

    Assume you want to suffix only keys with a in its value and you want the value replaced with the length of the set in such a case. Otherwise, the key-value pair should stay unchanged.

    dict((f"{k}_a", len(v)) if "a" in v else (k, v) for k, v in d.items())
    # {'key1_a': 3, 'key2': {'bar', 'foo'}, 'key3': {'sad', 'so'}}
    

提交回复
热议问题