Reputation: 23
I was showing off some python data types and their functions and attributes about them and one of them was a dictionary and I wanted to reassign the value at the first key and it did reassign it but it also moved the key and its value to a different position and I can't figure out why
I tried this on the Python shell and it gave me the expected result but when I was trying it on GDB online debugger, it gave me the unexpected and wrong results.
This is the snippet of the code that's acting unexpectedly:
a=[1, 2, 3, 3, 4]
b={'f':1, 's':2, 't':3, 'fo':4}
b['f']=0
a[0]=0
print(a, b)
What I expected was:
[1, 2, 3, 3, 4] {'f':0, 's':2, 't':3, 'fo':4}
What actually came out:
[0, 2, 3, 3, 4] {'s':2, 't':3, 'fo':4, 'f':0}
Upvotes: 1
Views: 48
Reputation: 13589
In Python <= 3.6, dict
s are unordered. You should not rely on the ordering of their elements.
In Python >= 3.7, dict
s are insertion-ordered. Updating existing values in the dict
should not affect the order.
In all versions >= 2.7, you can use collections.OrderedDict
if you need stable ordering.
Based on the behavior you described, I would bet that the GDB online version of Python is older than your local version, or you just got lucky when running locally.
Upvotes: 2
Reputation: 311188
Dictionaries in python don't have any guarantee about their order, so any order you see is purely coincedental. If you want to use a dictionary that preserves the order of elements, you could use an OrderedDict
:
from collections import OrderedDict
b = OrderedDict((('f', 1), ('s', 2), ('t', 3), ('fo', 4)))
Upvotes: 0