How to make PyCharm collapse/fold the dictionary constructor `dict()`?

Question:

I’m working in PyCharm, and to make my code more readable I’m using the Folding Code Elements (collapse/expand) feature.

Is there a way to collapse a dictionary, while still using the dict constructor dict(key=value)?

I’m aware that PyCharm allows code to be collapsed while using the dict literal {key: value} (see code example below).

I’d rather use the constructor for two reasons:

  1. Keys are set without quotes "", therefore cleaner;
  2. Keys are shown with a different color than values.

In case there is no way to collapse dict constructor, is there a good reason, other than efficiency difference between dict declaration methods, why I’d use dict literal rather than dict constructor?

Expanded code:

# literal
thisdict_1 = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

# constructor
thisdict_2 = dict(
    brand="Ford",
    model="Mustang",
    year=1964
)

Collapsed code:

# literal
thisdict_1 = {...}

# constructor
thisdict_2 = dict(
    brand="Ford",
    model="Mustang",
    year=1964
)
Asked By: Guilherme Loureiro

||

Answers:

The normal way in python is

a = {'key': 'value', 'other key': 'other value'}
Answered By: LtWorf

Use special comment <editor-fold desc="Description">

a = dict(
    # <editor-fold desc="Description">
    z=4,
    d=77
    # </editor-fold>
)
Answered By: Louis Saglio
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.