Reputation: 121
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
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
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