Printing data from a Python dictionary

Asked

Viewed 3,000 times

1

How do I print the data of a dictionary each in a column?

For example:

lanchonete = {"Salgado":4.50, "Lanche":6.50,"Suco":3.00,"Refrigerante":3.50,"Doce":1.00}

for m in lanchonete:
    print (m[0])

I want to print the snacks in one column and the values in another.

2 answers

8


An iteration with for in a dictionary always iterates only on the keys - so you didn’t see the values.

Dictionaries, however, in addition to being directly iterable have three methods that return specialized iterators: over the keys (.keys()), on values (.values()) or about both (.items()) - this last method returns the keys and sequence values of two items (tuples) - and can be used with the Augmented Python assignemnt that allows multiple variables to receive the item values of a sequence.

So you can do it like this:

lanchonete = {"Salgado":4.50, "Lanche":6.50,"Suco":3.00,"Refrigerante":3.50,"Doce":1.00}
for produto, preco in lanchonete.items():
     print(produto, preco)

If you want to add more symformations to what you are printing, a good request are the f-strings, which exist from Python 3.6:

for produto, preco in lanchonete.items():
     print(f"Produto {produto}: R${preco:0.02f}")
  • Poxa. I appreciate the help. Thank you very much.

6

There are several ways to do this, one of them would be like this:

lanchonete = {"Salgado" : 4.5, "Lanche" : 6.5, "Suco" : 3, "Refrigerante" : 3.5, "Doce" : 1}
for item in lanchonete:
    print("{0:20} {1:6.2f}".format(item, lanchonete[item]))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

This way you are using the function format() to set up the line by doing the padding text and correct number formatting also doing i padding and putting in the appropriate format (which I thought best).

  • Thank you very much. It helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.