Python学习笔记7:This dictionary creation could be rewritten as a dictionary literal

在使用Pycharm创建字典的时候,经常会看到如下提示:

This dictionary creation could be rewritten as a dictionary literal

截图:
《Python学习笔记7:This dictionary creation could be rewritten as a dictionary literal》

但是单独定义一个字典又没有这个提示:

《Python学习笔记7:This dictionary creation could be rewritten as a dictionary literal》

由此可见,这个和定义字典后,赋值键值对有关,即后面的第2行之后有关

解释如下:

链接1:https://stackoverflow.com/questions/8406242/why-does-pycharms-inspector-complain-about-d

链接2:https://youtrack.jetbrains.com/issue/PY-19269#u=1461253420326

解决方法:

1、不需要分行写

《Python学习笔记7:This dictionary creation could be rewritten as a dictionary literal》

2、使用dict()

《Python学习笔记7:This dictionary creation could be rewritten as a dictionary literal》

3、结合上面两个,使用update

方法1:

 1 storage = dict()  # 使用dict()
 2 storage.update({
 3     "first": {},
 4     "middle": {},
 5     "last": {}
 6 })
 7 
 8 names = {}  # 使用{}
 9 names.update({
10     "first": {},
11     "middle": {},
12     "last": {}
13 })
14 print("Storage:{}".format(storage))
15 print("Names:{}".format(names))

输出:

《Python学习笔记7:This dictionary creation could be rewritten as a dictionary literal》

    原文作者:七甲八甲
    原文地址: https://www.cnblogs.com/xlsxiaolaoshu/articles/8041322.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞