Is there another way to access the data from dictionary items()?


#1

Question

Is it possible to access the data from the dictionary items() function other than the for loop with two variables as shown in this exercise?

Answer

The results from the items() function are a Python tuple data type. You can use indexing to access the elements of the tuple. For a dictionary, the key would be index 0 and the value would be index 1. The following code example shows this usage for a simple dictionary.

letters = { "A": 10, "B": 20, "C": 30, "D": 40 }

for data in letters.items():
    print(data[0])
    print(data[1])