2

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
)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135

3 Answers3

1

I prefer to modify it like below as a hack with minimal typing:

a = {**dict(
    z=4,
    d=77
)}
  • Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit](https://stackoverflow.com/posts/76329792/edit) to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken May 27 '23 at 03:49
0

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

a = dict(
    # <editor-fold desc="Description">
    z=4,
    d=77
    # </editor-fold>
)
Louis Saglio
  • 1,120
  • 10
  • 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
  • 7,286
  • 6
  • 31
  • 45