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:
Keys
are set without quotes ""
, therefore cleaner;
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
)
Answers:
The normal way in python is
a = {'key': 'value', 'other key': 'other value'}
Use special comment <editor-fold desc="Description">
a = dict(
# <editor-fold desc="Description">
z=4,
d=77
# </editor-fold>
)
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:
Keys
are set without quotes""
, therefore cleaner;Keys
are shown with a different color thanvalues
.
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
)
The normal way in python is
a = {'key': 'value', 'other key': 'other value'}
Use special comment <editor-fold desc="Description">
a = dict(
# <editor-fold desc="Description">
z=4,
d=77
# </editor-fold>
)