Python 尝试从字典键格式化时出现 KeyError

Python KeyError from trying to format from dictonary key

我试图让您使用配置字典中其他键的值,但它不起作用,(抱歉,如果这是一个愚蠢的问题,我是来自 c++ 的 python 的新手)。我正在将它转换为 json 对象,因为它 returns 是一个字符串,您只能格式化字符串

代码:

import getopt, sys, json

def main():
    dicto = {"key":"yes", "cool":"{key}"}
    str_dicto = json.dumps(dicto)
    print(dicto)
    print(str_dicto.format(key = dicto["key"]))

if __name__ == "__main__":
    main()

错误:

C:\Users\MyUserName>python test.py

C:\Users\MyUserName>python test.py
{'key': 'yes', 'cool': '{key}'}
Traceback (most recent call last):
  File "C:\Users\MyUserName\test.py", line 10, in <module>
    main()
  File "C:\Users\MyUserName\test.py", line 7, in main
    print(str_dicto.format(key = dicto["key"]))
KeyError: '"key"'

错误提示多了一对括号

你这样做的话运气会更好:

import getopt, sys, json

def main():
    dicto = {"key":"yes", "cool": '{key}'}
    str_dicto = json.dumps(dicto)
    print(dicto)
    print(str_dicto.replace('{key}', dicto["key"]))

if __name__ == "__main__":
    main()

输出:

{'key': 'yes', 'cool': '{key}'}
{"key": "yes", "cool": "yes"}

这将实现与将 dict 转换为 str 而不是 json 转储它相同的效果

import getopt, sys, json

def main():
    dicto = {"key":"yes", "cool": '{key}'}
    str_dicto = str(dicto)
    print(dicto)
    print(str_dicto.replace('{key}', dicto["key"]))

if __name__ == "__main__":
    main()

输出:

{'key': 'yes', 'cool': '{key}'}
{'key': 'yes', 'cool': 'yes'}

另一种选择是使用 string.Template:

from string import Template

def main():
    dicto = {"key":"yes", "cool":'$key'}
    t = Template(str(dicto))
    str_dicto = t.substitute(key=dicto['key'])
    print(str_dicto)

if __name__ == "__main__":
    main()

打印:

{'key': 'yes', 'cool': 'yes'}