2

I'd like to use dict comprehensions and the ternary operator to create a new dict. Here is a MWE.

# Step 1: Create a dict, `d`
# {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j'}
import string
d = {k : v for k, v in zip(range(1, 11), string.ascii_lowercase[:10])}

# Step 2: Use dict comprehensions and the ternary operator to get a new dict
new_dict = {k : v if k<5 else v : k for k, v in d.items()}

but encounter this issue,

    new_dict = {k : v if k<5 else v : k for k, v in d.items()}
                                    ^
SyntaxError: invalid syntax

Why is SyntaxError rasied? How to fix it?

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134

2 Answers2

4

The key:value syntax is not a real expression, so you can't use the ternary operator on it. You need to do the ternary operation separately on the key and value parts:

new_dict = {(k if k<5 else v) : (v if k<5 else k) for k, v in d.items()}

(I changed you test to k<5 rather than v<5, assuming you want to compare the numerical keys to 5; comparing the string values to 5 won't work in Python 3 and will give meaningless results in Python 2.)

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

This is the correct syntax.

new_dict = {k if k < 5 else v : v if k < 5 else k for k, v in d.items()}
Vedang Mehta
  • 2,214
  • 9
  • 22