python - 将此字典重写为文字
问题描述
我目前正在尝试从元组创建字典,但 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
解决方案
(假设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]
推荐阅读
- hive - 如何计算impala hive中电子邮件地址中“@”的总出现次数
- microsoft-graph-api - 在守护进程上使用 Microsoft Graph 访问特定邮件帐户
- typescript - 带有严格由字符串联合类型组成的键的打字稿类型
- android - ViewPager 和 ImageGallery
- c# - 如果给定窗口句柄,我如何确定窗口句柄是否是 Windows UI 的一部分而不是应用程序?
- azure-devops - 如何指定哪个版本的 nuget.exe 与 Azure DevOps 中的自托管代理一起使用?
- pyspark - 如何创建具有行号inf pyspark的列
- apache-spark - 如何在火花中实现具有多个条件的try catch
- python - 将多个数据帧传递给函数
- google-apps-script - 在 Google 表格中创建行和根据用户输入填充数据的应用脚本代码中找不到错误