2

I'm working in PyCharm to make my code more readable, by Folding Code Elements (collapse/expand).

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

I'm aware that PyCharms allows code collapsing while using dict literal {key: value}. See code example bellow.

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
)

2 Answers2

0

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

a = dict(
    # <editor-fold desc="Description">
    z=4,
    d=77
    # </editor-fold>
)
Louis Saglio
  • 1,090
  • 14
  • 20
  • 1
    Tks it worked! Just found an alternative way with less charcters: `#region Description \n ... \n #endregion` [Using code folding comments](https://www.jetbrains.com/help/pycharm/2016.1/code-folding.html#using_folding_comments) – Guilherme Loureiro Dec 22 '18 at 18:27
-2

The normal way in python is

a = {'key': 'value', 'other key': 'other value'}
LtWorf
  • 6,904
  • 5
  • 30
  • 41