0

I'm trying to print a dictionary nicely. I have this

fruits = {'apple': 100,
          'banana': 2,
          'mango': 42}

I used print(fruit) but it just outputs: {'apple': 100, 'banana': 2, 'mango': 42}

Is there a way I can print it like this:

apple 100
banana 2
mango 42
Sarah Chan
  • 41
  • 1
  • 6

2 Answers2

3

This is one approach using str.join

Ex:

fruits = {'apple': 100,
          'banana': 2,
          'mango': 42}

fruits = "\n".join("{0} {1}".format(k, v)  for k,v in fruits.items())
print(fruits)

Output:

mango 42
apple 100
banana 2
Rakesh
  • 81,458
  • 17
  • 76
  • 113
3

You can use a simple for loop like this

for k,v in fruits.items():
    print(k, v)

Output

apple 100
banana 2
mango 42

To print in descending order:

for k,v in sorted(fruits.items(), key=lambda x: x[1], reverse=True):
    print(k,v)

Output:

apple 100
mango 42
banana 2
user3483203
  • 50,081
  • 9
  • 65
  • 94
Van Peer
  • 2,127
  • 2
  • 25
  • 35
  • How would I do it if I wanted to print it in descending order? So it prints apples first because it has 100 then mano because it was 42 then banana because it has 2 – Sarah Chan Aug 05 '18 at 07:33
  • 1
    You could sort `fruits.items()` like so: `sorted(fruits.items(), key=lambda x: x[1], reverse=True)` – user3483203 Aug 05 '18 at 07:35
  • @user3483203 Could you post it as an answer. I didn't quiet understand – Sarah Chan Aug 05 '18 at 07:39
  • @user3483203 what is lambda – Sarah Chan Aug 05 '18 at 07:45
  • @SarahChan SO is a treasurechest full of informations - research instead of asking q after q after q: [how to sort dictionary by key](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) and [why are lambdas usefull](https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful/890188#890188) – Patrick Artner Aug 05 '18 at 08:15