給出 Python 中變數名的列表,如何建立一個具有變數名稱作為鍵的字典 (到變數的值)

醋精測試媛發表於2020-12-23
name = 'foo'
zip1 = 123

message = dict([(x, locals()[x]) for x in ['name', 'zip1']])
print(message)

console:

Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/YangoManagementPlatformWebTest/common/mysql.py", line 103, in <module>
message = dict([(x, locals()[x]) for x in ['name', 'zip1']])
File "C:/Users/Administrator/PycharmProjects/YangoManagementPlatformWebTest/common/mysql.py", line 103, in <listcomp>
message = dict([(x, locals()[x]) for x in ['name', 'zip1']])
KeyError: 'name'

請問問題出在哪裡呢?

相關文章