1

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?

0

6 Answers 6

11

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().

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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.

Comments

1

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
>>> {}

Comments

1

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

Comments

1

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.

2 Comments

Well, this is an old question... Unfortunately, your answer is not correct - I was looking for a way to return an empty dict and to assign it to d[x] at the same time - something your code doesn't do (please check other answers). Still, +1 for the effort and welcome to SO!
Thanks for pointing out my mistake. I edited my answer to reflect its incomplete nature. Also, thanks for the warm welcome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.