0

How can I access the dictionaries key and value and iterate over for loop.

dictioanry= {1: "one", 2: "Two", 3:"Three"}

my output will be like:

1  one
2  two
3  three
gm03
  • 19
  • 2
  • 2
    Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – Numerlor Feb 02 '22 at 15:50
  • Welcome to Stack Overflow. If your question has been answered, you should see [What should I do when some answers my question](https://stackoverflow.com/help/someone-answers). – Muhammad Mohsin Khan Feb 02 '22 at 16:00

3 Answers3

2

You can use this code snippet.

dictionary= {1:"a", 2:"b", 3:"c"}

#To iterate over the keys
for key in dictionary.keys():
    print(key)

#To Iterate over the values
for value in dictionary.values():
    print(value)

#To Iterate both the keys and values
for key, value in dictionary.items():
    print(key,'\t', value)
Gowdham V
  • 292
  • 1
  • 4
1

Use dict.items():

Return a new view of the dictionary’s items ((key, value) pairs)

for key, value in dictioanry.items():
    print(key, value)

Side note: There is a typo in "dictioanry"

1

Do this to get the desired output:

dictionary= {1: "one", 2: "Two", 3:"Three"}

for i in dictionary.keys():
    print(i, dictionary[i])

Output:

>>> 1 one
2 Two
3 Three
Muhammad Mohsin Khan
  • 1,454
  • 6
  • 14
  • 22