0

How do I loop through a dictionary in Python?

I am trying to loop through a dictionary in Python, but I'm having trouble getting it to work. Here's what I've tried:

my_dict = {"apple": 1, "banana": 2, "orange": 3}

for item in my_dict:
    print(item)

I was expecting this code to print out the keys of the my_dict dictionary ("apple", "banana", and "orange"), but instead it only prints out the keys without their associated values:

apple
banana
orange

How can I modify my code to loop through the dictionary and print out both the keys and their associated values? Thank you.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367

1 Answers1

0

Iterating over my_dict is equivalent to iterating over its keys, you can iterate over both by iterating over my_dict.items()

my_dict = {"apple": 1, "banana": 2, "orange": 3}

for key, val in my_dict.items():
    print(f'{key}: {val}')

convolutionBoy
  • 811
  • 5
  • 18