简体   繁体   中英

How do I avoid a comma from being printed at the end of a dictionary being printed out?

I'm trying to print out a dictionary (with its respective key and value), but can't seem to figure out the formatting.

for key, value in dictionary.items():
    print(str(key) + ": " + "'" + str(value) + "'", end="")
    if counter > 1:
        print(", ", end="")

print("} ", end="")             

As you can see, I'm printing out the key, followed by a colon, followed by a single quote, followed by the value, and another single colon. The next if statement is there so that it can print a comma after each element of the dictionary. However, it prints out a comma after the last element. How do I avoid this?

It's not clear why you'd want to do this when str(dictionary) will do something similar, but with the proper repr for each key and value (eg, not pretending non-string values are strings, including recursively handling subdicts, and escaping any quotes in values that are strings, and so on), and without this problem. If you want nicer formatting, you can use pprint (or even, if your keys and values are JSON-compatible, json.dumps ).

But there are similar problems that can't be avoided so easily, so it's worth understanding how to do this.


Usually, the best answer is to build up a list or iterator of strings and join them:

pairs = []
for key, value in dictionary.items():
    pair.append(str(key) + ": " + "'" + str(value) + "'")
print(', '.join(pairs))

… or, if you prefer brevity:

print(', '.join(
    str(key) + ": " + "'" + str(value) + "'" for key, value in dictionary.items()))

When you can't do that for some reason (eg, because there are just way to many keys to store that list in memory), you can keep track of the length of the collection and explicitly skip the last one:

for i, (key, value) in enumerate(dictionary.items()):
    print(str(key) + ": " + "'" + str(value) + "'", end="")
    if counter > 1 and i != len(dictionary)-1:
        print(", ", end="")

… but it's usually better to move the , to the front, so you can skip the first one instead of the last, which works nicely even for generators and other iterables without lengths:

for i, (key, value) in enumerate(dictionary.items()):
    if counter > 1 and i > 0:
        print(", ", end="")
    print(str(key) + ": " + "'" + str(value) + "'", end="")

As a side note, if you have to convert things to str just to concatenate them, it's usually more readable to use an f-string (or, for earlier versions of Python, str.format ). For example, you can rewrite this:

str(key) + ": " + "'" + str(value) + "'"

… as:

f"{key}: '{value}'"

… or, for Python 3.5 or 2.7:

"{}: '{}'".format(key, value)

I'm not sure why you should use a loop. You can simply do str(dictionary) and it gives you a string as you like. If you don't like curly brackets, just remove them by index str(dictionary)[1:-1]

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