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
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
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)
Use dict.items()
:
Return a new view of the dictionary’s items (
(key, value)
pairs)
for key, value in dictionary.items():
print(key, value)
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