gpt4 book ai didi

python - 如何将 string.format 与嵌套字典一起使用

转载 作者:太空狗 更新时间:2023-10-29 21:25:49 25 4
gpt4 key购买 nike

我有一个嵌套的字典:

KEYS1 = ("A", "B", "C")
KEYS2 = ("X", "Y", "Z")

d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0))

我现在想使用格式将它的值嵌入到字符串中,例如

print("d['A']['X']={A,X:d}".format(**d))

输出:

d['A']['X']=0

那是行不通的。关于如何正确执行此操作的任何建议?

最佳答案

KEYS1 = ("A", "B", "C")
KEYS2 = ("X", "Y", "Z")

d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0))

print("d['A']['X']={A[X]}".format(**d))

输出:

d['A']['X']=0

从 python 3.6 开始,您将能够使用 Literal string interpolation 访问字符串中的字典。 :

In [23]: print(f"d['A']['X']={d['A']['X']}")
d['A']['X']=0

关于python - 如何将 string.format 与嵌套字典一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34442448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com