首页 > 解决方案 > 将此字典重写为文字

问题描述

我目前正在尝试从元组创建字典,但 PyCharm 告诉我我的字典可以重写为字典文字。我不知道怎么做。

这是 Python 2.7:

tb = traceback.extract_tb(ex_traceback)
my_stack = {'file': '', 'line': '', 'where': '', 'code': ''}
my_stack['file'], my_stack['line'], my_stack['where'], my_stack['code'] = tb[0]
print my_stack

标签: pythonpython-2.7

解决方案


(假设tb[0]是一个 4 元组或类似的)

以下将起作用,尽管它不完全是 dict 文字:

my_stack = dict(zip(("file", "line", "where", "code"), tb[0]))

不过,我认为 PyCharm 的意思是让你做这样的事情:

my_stack = {
    'file': tb[0][0],
    'line': tb[0][1],
    'where': tb[0][2],
    'code': tb[0][3],
}

这就是你的代码的第三行等价的,假设tb[0]是一个四元组。

如果您希望所有内容都具有相同的值,则可以链式 equals 代替:

my_stack['file'] = my_stack['line'] = my_stack['where'] = my_stack['code'] = tb[0]

推荐阅读