简体   繁体   English

打印格式化的字典键

[英]Printing a formatted dictionary key

Basically I want to print a value in a dictionary based on a separate variable. 基本上,我想根据单独的变量在字典中打印一个值。
For example: 例如:

d={"key1":5, "key2":5}  
x=2  
print("The value is {%d}".format(d["key{%d}".format(x)]))  

I would like this to output "The value is 5", but it tells me that %d is not part of the key. 我希望此输出“值为5”,但它告诉我%d不是键的一部分。 Is there 在那儿
any way to make it print what I want it to print? 有什么办法可以打印我想要打印的内容吗?

The problem is with the format strings. 问题在于格式字符串。 You are mixing the old-style % format strings with the new str.format method. 您正在将旧样式的%格式字符串与新的str.format方法混合str.format Use correct format strings and it will work: 使用正确的格式字符串,它将起作用:

>>> print("The value is {}".format(d["key{}".format(x)]))
The value is 5

or with old-style formatting: 或采用旧式格式:

>>> print("The value is %d" % d["key%d" % x])
The value is 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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