Scout721
Scout721

Reputation: 121

How to print a dictionary separated by commas

Let's say we have a dictionary

dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }

How would I go about printing the code so it looks like:

Dollar 12, Half-Coin 4, Quarter 3, Dime 7

Upvotes: 0

Views: 4695

Answers (3)

Volantines
Volantines

Reputation: 76

dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }

out=""
for i in dict:
    out += i+" "+str(dict[i])+", "

print out[:-2]

result:

Half-Coin 4, Quarter 3, Dollar 12, Dime 7

Upvotes: -1

Robᵩ
Robᵩ

Reputation: 168626

Use ','.join(), passing in a generator of strings.

d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,v) for k,v in d.items())

Result:

Half-Coin 4, Quarter 3, Dollar 12, Dime 7

If you want the results to be in a predictable order, you'll need to sort the items.

order=('Dollar', 'Half-Coin', 'Quarter', 'Dime')
d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,d[k]) for k in sorted(d, key=order.index))

Result:

Dollar 12, Half-Coin 4, Quarter 3, Dime 7

Ps. Don't name your variables with names of builtin types. Your name eclipses the builtin name, so subsequent code won't be able to call dict(), for example.

Upvotes: 5

userxxx
userxxx

Reputation: 796

", ".join([x +" "+str(dict[x]) for x in dict.keys()])

Upvotes: -1

Related Questions