简体   繁体   中英

Python KeyError from trying to format from dictonary key

I'm trying to let you use values from other keys in a configuration dictionary, but it doesn't work, (sorry if it's a stupid question im new to python coming from c++). I am converting it to a json object since it returns a string and you can only format strings

The code:

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()

The error:

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"'

Another option would be to use 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()

Prints:

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

The error is showing that there is an extra pair of brackets

You would have better luck doing this:

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()

Output:

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

Which would achieve the same thing as converting the dict to a str instead of json dumping it

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()

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM