Beware when using dict.keys() and dict.values()
Starting with Python3.7 dict.keys()
and dict.values()
preserves an insertion order [1] [2] [3].
That’s not true for older versions, so the code below
1 | data = { |
might show you an output notifying about unexpected order of items. The tricky part is that it might give you correct result in some cases (on your dev environment) and definitely will give you wrong result in other cases (production env).
Consider the following example
1 | process_data = lambda x: x**2 |
It will give you inconsistent results between run making your code unreliable.
Note that you can rely matching between
keys
andvalues
For example the code below will work
1 | def get_index_of(number): |
That means you still can safely use any index to value conversions keeping in mind only the fact you cannot be sure about the order of elements in these containers. But when in doubt make sure to use OrderedDict.
Happy coding!