georg
georg

Reputation: 214959

python ternary operator with assignment

I am new to python. I'm trying to write this

if x not in d:
    d[x] = {}
q = d[x]

in a more compact way using the ternary operator

q = d[x] if x in d else (d[x] = {})

but this gives the syntax error. What am I missing?

Upvotes: 1

Views: 7241

Answers (6)

Vlad Bezden
Vlad Bezden

Reputation: 89587

You can also use Python's dictionary get() method

q = d.get(x, {})

Explanation:

The get() method returns the value for the specified key if key is in a dictionary.

The syntax of get() is:

dict.get(key[, value]) 

get() Parameters

The get() method takes maximum of two parameters:

key - key to be searched in the dictionary

value (optional) - Value to be returned if the key is not found. The default value is None.

Return Value from get()

The get() method returns:

  • the value for the specified key if key is in dictionary.
  • None if the key is not found and value is not specified.
  • value if the key is not found and value is specified.

Another option is to use defaultdict

from collections import defaultdict

d = defaultdict(dict)
q = d[x]

>>> q
>>> {}

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601649

The conditional operator in Python is used for expressions only, but assignments are statements. You can use

q = d.setdefault(x, {})

to get the desired effect in this case. See also the documentation of dict.setdefault().

Upvotes: 11

user2027294
user2027294

Reputation: 13

For those interested in the ternary operator (also called a conditional expression), here is a way to use it to accomplish half of the original goal:

q = d[x] if x in d else {}

The conditional expression, of the form x if C else y, will evaluate and return the value of either x or y depending on the condition C. The result will then be assigned to q.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

That's what setdefault() is for:

q = d.setdefault(x, {})

It does exactly what you want:

  • Return d[x] if x is a key in d
  • Assign {} to d[x] if x is not yet a key and return that

Upvotes: 1

phihag
phihag

Reputation: 287835

In Python, assignments cannot occur in expressions, therefore you can't write code like a = (b = c).

You're looking for setdefault:

q = d.setdefault(x, {})

Alternative, use a defaultdict.

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993105

The reason that else (d[x] = {}) is a syntax error is that in Python, assignment is a statement. But the conditional operator expects expressions, and while every expression can be a statement, not every statement is an expression.

Upvotes: 3

Related Questions