0

How do I make a program that separates a dictionary such as in the format as: {"one":2, 3:4, "five":6, 7:8} into:

one: 2
3: 4
five: 6
7: 8

Each pair or key, value in a new line, with exception handling that can detect if a dictionary is empty or not a valid input.

I have thought about using loops but I'm not sure if that's necessary or even works.

Henrique Branco
  • 1,778
  • 1
  • 13
  • 40
StarTron
  • 1
  • 4

1 Answers1

0

Well, the easiest is a plain ol' loop:

d = {"one":2, 3:4, "five":6, 7:8}
for k, v in d.items():
  print(k, v, sep=": ")

You could also format the pairs in a list comprehension if that suits you better, but it's arguably less readable:

print(*[f"{k}: {v}" for (k, v) in d.items()], sep="\n")
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Ah thank you! But Im still not quite sure how to do the exception handling – StarTron Mar 27 '22 at 20:19
  • What exception handling do you need? If you want to print something if the dict is empty, wrap things in an `if d: ... else: print("Nothing in the dict")` – AKX Mar 27 '22 at 20:23