3

How can I access the dictionary's key and value and iterate over for loop?

dictionary = {1: "one", 2: "two", 3: "three"}

My output will be like:

1  one
2  two
3  three
wjandrea
  • 28,235
  • 9
  • 60
  • 81
gm03
  • 49
  • 1
  • 4
  • 3
    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

3 Answers3

8

You can use this code snippet.

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

# To iterate over the keys
for key in dictionary.keys():  # or `for key in dictionary`
    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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Gowdham V
  • 574
  • 3
  • 4
4

Use dict.items():

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

for key, value in dictionary.items():
    print(key, value)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Muhammad Mohsin Khan
  • 1,444
  • 7
  • 16
  • 23