# Real-World Tasks With Dictionary Iteration

Copied!
Happy Pythoning!

yasserkgl

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

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

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

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()}
``````

to join the conversation.