-1

I'm new to python. My current version of it is: 2.7.16 So, in the code I have a function:

def func (coords):
  xb, yb, xe, ye = coords.values()
  print(coords, 'order__') #1

Then I call it:

func({ 'xb': 0, 'yb': 0, 'xe': 40, 'ye': 20 })

But as I found out later I got an error somewhere because the things didn't work well. I added that print and it showed:

({'xb': 0, 'yb': 0, 'ye': 20, 'xe': 40}, 'order__')

So, as you see the order of properties changed and that causes the destructurisation to work not correctly. Two questions: 1. Why is it so? 2. What should I do to make my code work? My solution is to make like this:

xb = coords['xb']
yb = coords['yb']

and so on. But is there a better solution? May be I don't know about it yet

  • 1
    Dictionaries generally don't conserve order, unlike lists. It may have been changed in python3, I don't remember. Also can try `from collections import OrderedDict` – IcedLance Jul 19 '19 at 17:34
  • Possible duplicate of [Why is the order in dictionaries and sets arbitrary?](https://stackoverflow.com/questions/15479928/why-is-the-order-in-dictionaries-and-sets-arbitrary) – Alexander Santos Jul 19 '19 at 17:36
  • Refer [this thread](https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared) Possible duplicate. – bkyada Jul 19 '19 at 17:36
  • Actually, I don't need to keep the same order. I just want to destructurise exactly by the names. – Юрий Стражнов Jul 19 '19 at 17:44

2 Answers2

2

dict retains order only from python 3.7. For python versions prior to this, you can use OrderedDict

>>> from collections import OrderedDict
>>> dct = OrderedDict([('xb', 0), ('yb', 0), ('xe', 40), ('ye', 20)])
>>> func(dct)
Sunitha
  • 11,777
  • 2
  • 20
  • 23
1

Dictionaries in Python are not necessarily ordered, and although ordering may work on some versions in some circumstances, you should never count on it. If you want to unpack the values in order, there exists collections.OrderedDict. I don't know your situation, but maybe just use a tuple or list to hold it (since your values 'xb', 'yb', 'xe', and 'ye' seem to be the variable names as well as the keys. This seems like an XY problem).

101arrowz
  • 1,825
  • 7
  • 15