Questions on Dictionaries and Lists

  1. Why the first for loop is working and not the second one? Whats the purpose of .items()?
    a. Working for Loop

b. Error for loop


 dict = {'a':1,'b':2}

for item in dict:
for item in dict:
1 Like

If you iterate through the results of the .items() method of a dictionary it returns each key: value pair as a series of tuples. So if you wanted to use both key and value it’s not uncommon to call .items() in order to loop through them.

Without this argument though it defaults to same style as .keys() which only iterates through the keys, not the values (the other typical view used is .values()).
Check the docs for the details-

1 Like

So does that mean without dict.items() I cant print the key and value at the same time

You can use the following if you wanted to print both the key and value without using .items().

d = {1: 'a', 2: 'b', 3: 'c'}

for x in d:
  print(x, d[x])

The above would result in the following.

1 a
2 b
3 c

This way you are simply printing the key, then the result of using that same key to access its corresponding value in d.

However, using .items() can make your code more clear and understandable. It’s faster and easier to tell that a key and its corresponding value are printed if, for example, you used print(key, value) rather than print(key, my_dict[key]). Using .items() also creates a pair of variables (key, value) that you can use to access key and values more easily, whether individually or paired.

1 Like