Print data from a dictionary in Python

0

How do I print data from 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 on one column and the values on another.

    
asked by anonymous 05.11.2018 / 15:26

2 answers

8

An iteration with for in a dictionary always iterates only over the keys - so you did not see the values.

Dictionaries, however, in addition to being directly iterated, have three methods that return specialized iterators: on the keys ( .keys() ), on the values ( .values() ) or on both ( .items() ) - the latter 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 definitions to what you are printing, a good request is the f-strings, which exist from Python 3.6:

for produto, preco in lanchonete.items():
     print(f"Produto {produto}: R${preco:0.02f}")
    
05.11.2018 / 17:00
6

There are several ways to do this, one of which would look 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]))

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

In this way you are using format() to mount the line by doing padding and the correct formatting of the number also doing i padding and putting it in the appropriate format (which I found the best).

    
05.11.2018 / 15:54