Skip to main content
 首页 » 编程设计

python之如何使 PyCharm 折叠/折叠字典构造函数 `dict()`

2025年05月04日9bjzhanghao

我在 PyCharm 中工作,为了使我的代码更具可读性,我使用了 Folding Code Elements (折叠/展开)功能。

有没有办法折叠字典,同时仍然使用字典构造函数dict(key=value)?

我知道 PyCharm 允许在使用字典文字 {key: value} 时折叠代码(请参见下面的代码示例)。

我宁愿使用构造函数有两个原因:

  1. Keys 不带引号 "",因此更简洁;
  2. Keys 显示的颜色与 values 不同。

如果没有办法折叠 dict constructor,除了 efficiency difference between dict declaration methods 之外还有其他充分的理由吗? ,为什么我要使用 dict literal 而不是 dict constructor?

扩展代码:

# literal 
thisdict_1 = { 
    "brand": "Ford", 
    "model": "Mustang", 
    "year": 1964 
} 
 
# constructor 
thisdict_2 = dict( 
    brand="Ford", 
    model="Mustang", 
    year=1964 
) 

折叠代码:

# literal 
thisdict_1 = {...} 
 
# constructor 
thisdict_2 = dict( 
    brand="Ford", 
    model="Mustang", 
    year=1964 
) 

请您参考如下方法:

使用特殊注释<editor-fold desc="Description">

a = dict( 
    # <editor-fold desc="Description"> 
    z=4, 
    d=77 
    # </editor-fold> 
)