在 python 中格式化字符串化字典时出现关键错误

Getting a key error while formatting a stringified dictionary in python

代码行:

data = '{"username": {u}, "password": {p}}'.format(u=user_name, p=password)

我只想在上面的字符串化字典中的 up

位置插入变量 user_namepassword

错误:

data = '{"username": {u}, "password": {p}}'.format(u=user_name, p=password)
KeyError: '"username"'

我也试过: data = f'\{"username": {user_name}, "password": {password}\}'

但这似乎没有用。

还有其他解决方法吗?

您需要 加倍 大括号以在 str.format patterns 中转义它们。

虽然代码很奇怪,但您为什么要尝试将内容插入到字符串化的伪字典中,而不是将最终字典字符串化,例如json.dumps({'username': u, 'password': p})

因为这里您的数据项的内容将是 "raw" 例如假设 user_name="billy bob"password="george" 你正在做的是

'{"username": billy bob, "password": george}'

这对我来说意义不大。

当您想在 f 弦中包含 {} 时,我们只需将它们加倍即可。

所以下面给出了你想要的输出。

>>> username = "foo"
>>> password = "bar"
>>> f'{{"username": {username}, "password": {password}}}'
'{"username": foo, "password": bar}'