简体   繁体   中英

Python: can't print dictionary key and value

This is a very simple block of code and I don't understand what I'm doing wrong:

import sys

o_dict = {'a': 10, 'b': 0, 'c': 20}
for key, val in o_dict.iteritems():
    if val < 1:
        sys.exit("Key: {}, Val: {}.").format(key, val)

I'd expect the output to be:

Key: b, Val: 0.

but instead it's always:

Key: {}, Val: {}.

What's happenning?

You have your format method on the exit method, not on the string. This is what you have:

sys.exit("Key: {}, Val: {}.").format(key, val)
#                           ^ wrong

this is what you want:

sys.exit("Key: {}, Val: {}.".format(key, val))
#                                            ^ right

错字:

sys.exit("Key: {}, Val: {}.".format(key, val))

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