Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Real-World Tasks With Dictionary Iteration

yasserkgl on May 26, 2020

hello

I tried to test thed same as you have explained but i find the below

prices={'orange':4, 'apple': 3, 'banana':7}
for key in prices:
    prices[key] = prices[key] + 2
    print(prices)

output

{'orange': 6, 'apple': 3, 'banana': 7}
{'orange': 6, 'apple': 5, 'banana': 7}
{'orange': 6, 'apple': 5, 'banana': 9}

Why it is repeated 3 times?

yasserkgl on May 26, 2020

Hellow

i follow the same example as you have explained but the output with some error

#inverse key with value
dic5={'red':7 ,"blue":8,"black":9 , "orange":22}
for key ,value  in dic5.items():
    dic5[value]=key
print(dic5)

output

Traceback (most recent call last): File “D:/Users/y.moneim/PycharmProjects/untitled2/Test002.py”, line 68, in <module> for key ,value in dic5.items(): RuntimeError: dictionary changed size during iteration

joshengroff on Aug. 22, 2020

You put print(prices) inside your for loop which prints out the updated dictionary the number of times it was iterated over (3).

Try it like this:

prices={'orange':4, 'apple': 3, 'banana':7}
for key in prices:
    prices[key] = prices[key] + 2

print(prices)

Liam Pulsifer RP Team on Aug. 23, 2020

Well said @joshengroff, and sorry to miss your comments @yasserkgl. The reason you’re seeing the error you mentioned above is because you’re iterating through your dictionary while changing it – this makes the Python runtime unsure of what items to include in the iteration. When you swap the keys and values in a dictionary, it’s normally much easier to make a new dictionary with the swapped items, like so:

d = {'a': 5, 'b': 6, 'c': 7}
swapped_d = {value: key for key, value in d.items()}

Become a Member to join the conversation.