简体   繁体   中英

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. 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. 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

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