Reputation: 16870
Can I be sure about the order in a Python dictionary?
The function op.GetTangent(id)
returns a dictionary containing two values associated with 'vl'
and 'vr'
. I want to unpack it the lazy way.
vr, vl = op.GetTangent(id).values()
Can I be sure that vr
and vl
have the correct value or can there be a case where they're exchanged?
Upvotes: 3
Views: 95
Reputation: 95652
Just for the complete avoidance of any doubt whatsoever, actual output on my system:
C:\Python32>python -c "print({'vr':1, 'vl':2})"
{'vr': 1, 'vl': 2}
C:\Python32>python -c "print({'vr':1, 'vl':2})"
{'vl': 2, 'vr': 1}
That is running Python 3.2.3 with PYTHONHASHSEED set to 'random' and different runs of identical code have different orders of items in the dictionary.
Upvotes: 1
Reputation: 6625
No, you should never depend on the order of the entries returned by the values
method. You have several easy options:
sorted
on the resulting list (if the values can be sorted)sorted
on the items and pull out the valuescollections.OrderedDict
Upvotes: 6
Reputation: 91017
No, never.
Instead do
getbyname = lambda d, *kk: [d[k] for k in kk]
and use it as
vr, vl = getbyname(op.GetTangent(id), 'vr', 'vl')
or just do
d = op.GetTangent(id)
vr, vl = [d[i] for i in ('vr', 'vl')]
if you need it only once.
Upvotes: 3