Iterate the keys and values from the dictionary

Question:

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
Asked By: gm03

||

Answers:

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)
Answered By: Gowdham V

Use dict.items():

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

for key, value in dictionary.items():
    print(key, value)
Answered By: Anton Yang-Wälder

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
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.